Detect bash script source vs. direct execution
如何判断脚本是在当前shell下运行还是在子shell下面运行?
jan@jack:~/tmp> cat source.sh
function is_subshell() {
test "`basename $1`" = "source.sh" && return 1
return 0
}
function my_function() {
echo my_function
}
is_subshell $0 && my_function
jan@jack:~/tmp> cat src_parent.sh
echo -n "sourcing ... "
. ./source.sh
echo
echo -n "calling from bash ... "
bash ./source.sh
echo
echo -n "calling directly ... "
./source.sh
echo
jan@jack:~/tmp> ./src_parent.sh
sourcing ... my_function
calling from bash ...
calling directly ...
下列脚本的输出:
cat ./test.sh
echo $0
操作系统为Freebsd8.4
root sh下面
source ./test.sh显示_su
./test.sh 显示./test.sh
bash下面
source ./test.sh以及 . ./test.sh 显示 bash
./test.sh 显示./test.sh
浙公网安备 33010602011771号