LoginSignup
6
5

More than 5 years have passed since last update.

シェルスクリプトで実行ファイルの絶対パスを取得する

Posted at

これで実行ファイルのパスが取得できる

dir=$(cd $(dirname $0); pwd)

順を追っていくと覚えやすい

1

実行ファイルのディレクトリを取得

dirname $0

2

実行ファイルのディレクトリに移動

cd '実行ファイルのディレクトリ'

3

現在位置のディレクトリを取得

pwd

評価順序

結果を見てわかる通り、1番深い$()の内側のコマンドから順に処理されていく
途中の;は単にcdpwdを区切っているだけ

出力結果

例えばこのような環境下で実行した場合

$ tree
.
└─tmp
    └─ test.sh
$ cat tmp/test.sh
#!/bin/sh
echo $0
echo $(dirname $0)
echo $(cd $(dirname $0); pwd)

以下のような結果になる

$ sh tmp/test.sh
tmp/test.sh
tmp
/home/user/tmp

tmpから実行すると

$ cd tmp
$ sh test.sh
test.sh
.
/home/user/tmp
6
5
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
6
5