博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Detect bash script source vs. direct execution

http://www.linuxquestions.org/questions/programming-9/detect-bash-script-source-vs-direct-execution-685193/

如何判断脚本是在当前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