3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ls -Rでフルパスを取得

Last updated at Posted at 2016-09-26

あってもおかしくないのに、見当たらなかったので。
私の探し方がまずかったのかな…?
念のため、備忘録おいときます。

find -ls -maxdepth (n)

一番手っ取り早いのはこれ。
とはいえ、ls -Rの出力形式のようにしたい場合はfindは邪魔になります。
力技でいい感じにするというのも手ではありますが、今回はlsにこだわります。

キーポイント

ターミナルでpwdを打つ機会は多いと思いますが、$PWDで自分の場所がフルパスで取れます。
$(PWD)でもPWDでも同じです。

これを使って、今いる場所(./)をフルパスに置き換える、というのが目的です。
仕組み自体はそんな難しくないです。

fullls.sh
# !/bin/sh
nowDir=$PWD

cd $(dirname "lsで取りたいディレクトリ")
ls -R $PWD

cd ${nowDir}

これだけです。とても簡単!
nowDirしているのは、lsした後で今いる場所に戻ってくることがあるかも知れないので、念のため入れてます。

気をつけてほしいのが、nowDirでsh実行をする想定でteeとかしたい場合は以下のようにします。

tee.sh
# !/bin/sh

# shファイルのフルパスをthisに持っておく
cd $(dirname ${0})
this=$(PWD)

...
ls -R $PWD | tee ${this}/tee.txt

これでどこに移動しても一意の場所を設定できます。
結構落とし穴なので、出力先の設定も絶対パスにするようにしましょう。
逆に、相対パスで都合がいい場合はこの限りではありませんが、運用に気をつけてください。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?