我希望有一个功能,.bash_login
当当前终端是 XTerm 而不是 Terminology 时,它会显示文本。当我echo $TERM
在 Terminology 中执行此操作时,它xterm
会输出如何区分它们?
答案1
我不知道这是否是“正确”的方法,但您可以通过调用ps
通过 shell 内置命令获得的父进程 ID来找到调用父终端的命令$PPID
,例如
# get the shell's parent command from the PPID via ps
pcomm=$(ps -ocomm= $PPID)
然后,您可以测试命令字符串的值 - 例如使用 case 语句
# now do something based on the value of the parent terminal command
case "$pcomm" in
"gnome-terminal")
echo "parent is gnome-terminal"
;;
"xterm")
echo "parent is xterm"
;;
"terminator")
echo "parent is terminator"
;;
*)
echo "unknown parent terminal"
;;
esac
答案2
这是另一种(在我看来更简单)的方法。我没有 Enlightenment,所以我无法在 Terminology 上测试它,但我用 gnome-terminal、terminator 和 xterm 测试了它。
terminalPID=$(ps -o ppid= $PPID) # get the script's parent's PID (the terminal)
processName=$(ps -p $terminalPID -o comm=) # get the terminal's name by it's PID
terminalName='gnome-terminal' # specify what process name you want to check for
# do the checking
if [ $processName == $terminalName ] ; then
echo "You are using gnome-terminal!"
else
echo "You are using something else!"
fi
现在,为了找出终端的进程名称,请打开终端并运行
ps -p $PPID -o comm=
这将打印出终端的进程名称(当然,前提是您正在运行 bash)。
更完整的版本可以检查我已安装的几个不同的终端仿真器:
terminalPID=$(ps -o ppid= $PPID) # get the script's parent's PID (the terminal)
processName=$(ps -p $terminalPID -o comm=) # get the terminal's name by it's PID
# do the checking
if [ $processName == 'gnome-terminal' ] ; then
echo "You are using gnome-terminal!"
elif [ $processName == 'xterm' ] ; then
echo "You are using xterm!"
elif [ $processName == '/usr/bin/termin' ] ; then
echo "You are using Terminator!"
else
echo "You are using something else!"
fi