试一试,看看它是否符合您的要求:
#!/bin/sh
if [ $_ != $0 ]
then
echo interactive;
else
echo noninteractive;
fi
下划线 ( $_
) 扩展为用于调用脚本的绝对路径名。零 ( $0
) 扩展为脚本的名称。如果它们不同,则从交互式 shell 调用脚本。在 Bash 中,后续的扩展$_
将扩展参数提供给前一个命令(将 的值保存$_
在另一个变量中以保留它可能是个好主意)。
来自man bash
:
0 Expands to the name of the shell or shell script. This is set
at shell initialization. If bash is invoked with a file of com‐
mands, $0 is set to the name of that file. If bash is started
with the -c option, then $0 is set to the first argument after
the string to be executed, if one is present. Otherwise, it is
set to the file name used to invoke bash, as given by argument
zero.
_ At shell startup, set to the absolute pathname used to invoke
the shell or shell script being executed as passed in the envi‐
ronment or argument list. Subsequently, expands to the last
argument to the previous command, after expansion. Also set to
the full pathname used to invoke each command executed and
placed in the environment exported to that command. When check‐
ing mail, this parameter holds the name of the mail file cur‐
rently being checked.