终端窗口标题可以通过更改变量的值$PS1
-主提示字符串来更改。[1] [2]。我们可以将此解决方案与使用Dessert的答案中的命令的想法结合起来。 history
方法1:$PS1
自动更新值。(更新)
将以下行添加到文件的底部~/.bashrc
:
# Change the terminal window title, based on the last executed command
rtitle() {
# If the variable $PS1_bak is unset,
# then store the original value of $PS1 in $PS1_bak and chang $PS1
# else restore the value of $PS1 and unset @PS1_bak
if [ -z "${PS1_bak}" ]; then
PS1_bak=$PS1
PS1+='\e]2;$(history 1 | sed "s/^[0-9 ]* \+//")\a'
else
PS1=$PS1_bak
unset PS1_bak
fi
};
export -f rtitle # Export the function to be accessible in sub shells
#rtitle # Uncomment this line to change the default behaviour
然后source ~/.bashrc
或者只是打开一个新终端并以这种方式使用该功能:
- 执行
rtitle
以根据最后执行的命令自动开始更改终端窗口标题。
rtitle
再次执行以返回默认行为。
方法2:$PS1
手动更新值。(初始答案)
将以下行添加到文件的底部~/.bashrc
:
set-title() { # Set a title of the current terminal window
[[ -z ${@} ]] && TITLE="$(history 2 | head -1 | sed "s/^[0-9 ]* \+//")" || TITLE="$@" # If the title is not provided use the previous command
[[ -z ${PS_ORIGINAL} ]] && PS_ORIGINAL="${PS1}" || PS_ORIGINAL="${PS_ORIGINAL}" # Use the original value of PS1 for each future change
PS1="${PS_ORIGINAL}"'\e]2;'"$TITLE"'\a' # Change the prompt (the value of PS1)
}; export -f set-title
然后source ~/.bashrc
或者只是打开一个新终端并以这种方式使用该功能:
set-title <something>
将终端窗口标题更改为<something>
。
set-title
不带参数的终端窗口标题将更改为上一个命令。
参考和示例: