Unixでスクリプトイニシエータを見つける方法

Unixでスクリプトイニシエータを見つける方法

ファイルの実行がどのように開始されるかを知る方法があるかどうか疑問に思います。

たとえば、次のファイルを考えてみましょう。

~/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.shb.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

ご覧のとおり、sourcedファイルの呼び出し元は"${BASH_SOURCE[1]}"

おすすめ記事