脚本以“源”或“可执行”开始?

DrB*_*eco 6 executable shell-script

我们可以在脚本内部确定它是以source(.) 还是executable(shebang 或类似的东西)开头的?

Ant*_*hon 2

测试一下$0你是否有脚本:

#!/bin/bash
echo $0
Run Code Online (Sandbox Code Playgroud)

并使其可执行 ( chmod 755 test.sh) 并执行以下操作:

source test.sh
Run Code Online (Sandbox Code Playgroud)

你会得到bash(或者其他东西,取决于你的登录方式和你的 shell 是什么)。

如果你这样做

./test.sh
Run Code Online (Sandbox Code Playgroud)

你得到了./test.sh,所以假设脚本知道它是如何保存在光盘上的,你应该这样做:

if [ $(basename "$0") == "test.sh" ] 
then
   ..... your code here for non-sourced
else
   ..... your code here for sourced
fi
Run Code Online (Sandbox Code Playgroud)