ファイルの実行がどのように開始されるかを知る方法があるかどうか疑問に思います。
たとえば、次のファイルを考えてみましょう。
~/foo.sh
echo "Hello from foo.sh"
# print the name of the initiator/parent of this execution
~/bar.sh
source ~/foo.sh
~/baz.sh
. ~/foo.sh
私が走るとき
sh ~/bar.sh
または印刷する必要があります.~/bar.sh
。~/foo.sh
~/bar.sh
sh ~/baz.sh
または印刷する必要があります.~/baz.sh
。~/foo.sh
~/baz.sh
bash
私は一般的に言おうとしていますが、またはに固有のものかもしれませんzsh
。
ベストアンサー1
解決策は次のとおりですbash
(#!/bin/bash
最初の行またはで実行されるスクリプトの場合bash script...
)。
設定例(スクリプト2a.sh
とb.sh
):
cat >a.sh <<'x' && chmod a+x a.sh
#!/bin/bash
echo This is a.sh
source b.sh
echo End a.sh
x
cat >b.sh <<'x' && chmod a+x b.sh
#!/bin/bash
echo This is b.sh
echo "BASH_SOURCE=(${BASH_SOURCE[@]}) and we are '${BASH_SOURCE[0]}' called by '${BASH_SOURCE[1]}'"
echo End b.sh
x
ここでコードを実行して出力を確認してください。
./a.sh
This is a.sh
This is b.sh
BASH_SOURCE=(b.sh ./a.sh) and we are 'b.sh' called by './a.sh'
End b.sh
End a.sh
ご覧のとおり、source
dファイルの呼び出し元は"${BASH_SOURCE[1]}"
。