Answers:
根据man bash:
如果bash是交互式的,则设置PS1,并且$-包含i,从而允许shell脚本或启动文件测试此状态。
因此,您可以使用:
if [[ $- == *i* ]]
then
    do_interactive_stuff
fi
也:
启动不是登录外壳程序的交互式外壳程序时,如果存在这些文件,则bash从/etc/bash.bashrc和〜/ .bashrc中读取并执行命令。
因此~/.bashrc仅源于交互式外壳。有时,人们会从中获取~/.bash_profile或发现~/.profile它不正确,因为它会干扰预期的行为。如果要简化通用代码的维护,则应使用一个单独的文件来包含通用代码,并独立于两个rc文件获取其源代码。
最好不要从rc诸如~/.bash_profile或的登录文件输出到stdout,~/.profile因为它可能会干扰rsync例如的正确操作。
无论如何,测试交互性仍然是一个好主意,因为可能存在错误的配置。
[[ $- =~ i ]] && echo interactive
                    i
                    ~/.bash_profile或发现~/.profile它不正确,因为它会干扰预期的行为。您如何看待采购的~/.bashrc距离~/.bash_login?由于登录外壳不必是交互式的,我想这也是不正确的。
                    采用:
if tty -s; then echo interactive; fi该test工具可以对此进行检查(从手册页中进行检查):
-t FD True if FD is opened on a terminal.
因此,您可以使用例如:
 if [ -t 0 ] ; then
    echo stdin is a terminal
   .....
 fi
要么
if [ -t 1 ] ; then
    echo stdout is a terminal
 fi
bash <<< 'test -t 0 && echo Y || echo X'写Y,bash -c 'test -t 0 && echo Y || echo X'写X