Help us understand the problem. What is going on with this article?

$0と$BASH_SOURCEの違い

More than 3 years have passed since last update.

スクリプトを準備

$ 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)でいける

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away