これ受け入れられた回答同様の問題にはbash
機能しないようですzsh
。実際には、その答えに与えられた同じコードをデフォルトでコピーしてスクリプトを生成すると、
#!/usr/bin/zsh -
# test.sh
[[ $_ != $0 ]] && echo "sourced\n" || echo "subshell\n"
出力は現実とほとんど一致しません。
zsh% chmod +x ./test.sh
zsh% env -i /usr/bin/zsh -f
zsh% ./test.sh
sourced
zsh% /usr/bin/zsh ./test.sh
sourced
zsh% /bin/bash ./test.sh
sourced
zsh% source ./test.sh
subshell
zsh% . ./test.sh
subshell
zsh% env -i /bin/bash --norc --noprofile
bash-3.2$ ./test.sh
sourced
bash-3.2$ /usr/bin/zsh ./test.sh
sourced
bash-3.2$ /bin/bash ./test.sh
sourced
bash-3.2$ source ./test.sh
sourced
bash-3.2$ . ./test.sh
sourced
現在の対話型シェルがある場合、スクリプトzsh
は毎回完全に間違った結果を得ます。パフォーマンスが少し優れていますbash
(ただし、1日に2回正確に時間を維持するストップウォッチを思い出させますが)。
これらは実際にひどい結果を見ると、このアプローチに対する確信はほとんどありません。
もっと良いものがありますか?
ベストアンサー1
if [[ $ZSH_EVAL_CONTEXT == 'toplevel' ]]; then
# We're not being sourced so run the colors command which in turn sources
# this script and uses its content to produce representative output.
colors
fi
カーティスレッドzsh-usersメーリングリストから。