If you run test1.sh, you'll see
test1.sh
test1.sh
exit
If you run test2.sh, you'll see
test2.sh
test1.sh
test1.sh
#!/bin/sh
echo $0
echo $BASH_SOURCE
if [ $0 = $BASH_SOURCE ]; then
echo "exit"
exit 0;
fi
test2.sh
#!/bin/sh
. test1.sh
本文通过两个具体的Shell脚本测试示例,展示了如何在不同情况下使用$0和$BASH_SOURCE变量来区分脚本的直接运行与被调用状态。通过对比test1.sh和test2.sh的输出结果,读者可以理解在Shell脚本中这些变量的作用。
If you run test1.sh, you'll see
test1.sh
test1.sh
exit
If you run test2.sh, you'll see
test2.sh
test1.sh
test1.sh
#!/bin/sh
echo $0
echo $BASH_SOURCE
if [ $0 = $BASH_SOURCE ]; then
echo "exit"
exit 0;
fi
test2.sh
#!/bin/sh
. test1.sh
3831
1688

被折叠的 条评论
为什么被折叠?