确定 bash_profile 是通过登录还是通过脚本获取的?

确定 bash_profile 是通过登录还是通过脚本获取的?

我有许多依赖于文件中设置的环境变量的脚本.bash_profile

我还想在登录服务器时显示特定消息,我也将其添加到了.bash_profile.但是,当脚本调用时,我不希望显示此消息。

我知道我可以只使用source ~/.bash_profile > /dev/null 2>&1,但这会涉及到检查所有脚本,这很乏味 - 所以我想知道是否有一种方法可以确定脚本的来源。

我的目标是这样的(伪代码):

#FROM_TERMINAL should be set to 1 if ran by the user (logging into the server) - otherwise it stays empty.
if [[ $FROM_TERMINAL = 1 ]]; then
    echo "some message"
else
    :
fi

有没有一种优雅的方法来做到这一点?

谢谢你!

答案1

在 中man bash,它说道:

An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option.
PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

$-标志包含 shell 选项集,并在以下位置进行解释: https://tldp.org/LDP/abs/html/internalvariables.html

检查变量的内容,$-如下所示:

$ echo "$-"
himBHs

确定是否i设置如下:

if [[ $- == *i* ]]
then
    # I was called interactively, do the echoing etc.
fi

您还可以检查$PS1var 是否已设置,我发现这不太可靠。看https://tldp.org/LDP/abs/html/intandnonint.html#IITEST

相关内容