# 设置screen窗口标题,这个方式不依赖screenrc中的shelltitle if [ -n "$STY" ]; then# 仅在 screen 中生效 # 获取后台作业命令 __get_fg_cmd() { local job_id if [[ "$*" =~ ([0-9]+) ]]; then job_id="${BASH_REMATCH[1]}" else job_id="%+" fi temp_file="/tmp/jobs_$$" jobs"$job_id" 2>/dev/null > "$temp_file"
local line if IFS= read -r line < $temp_file; then if [ -n "$line" ]; then set -- $line if [ $# -gt 2 ]; then shift 2 RESULT="$*" rm -f $temp_file return fi fi fi RESULT="" rm -f $temp_file }
__get_vim_cmd() { local input="$*" if [[ $input =~ [[:space:]]+([^-][^[:space:]]*) ]]; then local name="${BASH_REMATCH[1]}" name="${name##*/}" RESULT="[vim]$name" else RESULT="vim" fi } __get_cmd() { local i local _command local _sudo=0 local _extract=1 _command="$BASH_COMMAND" for i in {0..4}; do # 清除前缀空格 _command="${_command#"${_command%%[![:space:]]*}"}" case "$_command" in "printf"*) return ;; "fg"|"fg"*) __get_fg_cmd $_command _command="${RESULT}" ;; "vim"|"vim "*) __get_vim_cmd $_command _command="${RESULT}" # vim不继续处理 _extract=0 break ;; "sudo "*) # sudo 删除 _command=${_command#* } _sudo=1 ;; *) # 跳出循环 break ;; esac done # 循环结束提取命令名 if [ $_extract -eq 1 ];then _command="${_command##*/}" _command="${_command%% *}" fi # sudo标记 if [ $_sudo -ne 0 ];then RESULT="#${_command}" else RESULT="${_command}" fi }
# 设置标题函数 __set_screen_title() { __get_cmd local cmd=${RESULT} if [ x${cmd} != x ];then printf"\033k${cmd}\033\134" fi }
# 设置触发器 trap'__set_screen_title' DEBUG # 一些发行版会使用PROMPT_COMMAND改变终端窗口标题,保留原ANSI序列。增加返回screen默认标题bash __prompt="printf '\033kbash\033\134'" if [[ -z "$PROMPT_COMMAND" ]];then PROMPT_COMMAND="$__prompt" elif [[ "$PROMPT_COMMAND" != *"$__prompt"* ]];then PROMPT_COMMAND="$PROMPT_COMMAND;$__prompt" fi fi