43
31

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.

$0と$BASH_SOURCEの違い

Last updated at Posted at 2017-10-01

スクリプトを準備

$ cat << 'EOF' > test
> echo $0
> echo $BASH_SOURCE
> echo ${BASH_SOURCE:-$0}
> EOF
$ chmod 777 test

実行してみる

$ ./test
./test
./test
./test
$ bash ./test
./test
./test
./test
$ source ./test
-bash
./test
./test
$ zsh test
./test

./test

sourceで実行されても、bashでもzshで実行されてもうまく実行ファイルのパスを取得するためには、BASH_SOURCE:-$0と書くべき
実行ファイルのディレクトリの絶対パスを取得するにはecho $(cd $(dirname ${BASH_SOURCE:-$0}); pwd)でいける

43
31
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
43
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?