如何将终端标题更改为当前正在运行的进程?

发布于 2025-01-13 21:20:54 字数 434 浏览 2 评论 0原文

我知道如何更改终端窗口标题。我试图找出的是如何使 bash 而不是 zsh 写出当前正在运行的进程,所以如果我说 do

$ ls -lF

我会得到类似这样的标题

/home/me/curerntFolder (ls -lF)

获取最后执行的命令会太晚了,因为命令已经执行了,所以它不会用命令设置标题那被处决了。

I know how to change the Terminal Window title. What I am trying to find out is how to make bash not zsh write out the currently running process so if I say do

$ ls -lF

I would get something like this for the title

/home/me/curerntFolder (ls -lF)

Getting the last executed command would be too late since the command has executed already, so it won't set the title with the command that was executed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

友谊不毕业 2025-01-20 21:20:54

除了 @markp-fuso 的答案之外,我还介绍了如何使其与 Starship 一起使用。

  function set_win_title() {
local cmd=" ($@)"
if [[ "$cmd" == " (starship_precmd)" || "$cmd" == " ()" ]]
then
cmd=""
fi
if [[ $PWD == $HOME ]]
then
if [[ $SSH_TTY ]]
then
echo -ne "\033]0;

In addition to @markp-fuso's answer, here's how I did it to make it work with Starship.

  function set_win_title() {
    local cmd=" ($@)"
    if [[ "$cmd" == " (starship_precmd)" || "$cmd" == " ()" ]]
    then
      cmd=""
    fi
    if [[ $PWD == $HOME ]]
    then
      if [[ $SSH_TTY ]]
      then
        echo -ne "\033]0; ????️ @ $HOSTNAME ~$cmd\a" < /dev/null
      else
        echo -ne "\033]0; ???? ~$cmd\a" < /dev/null
      fi
    else
      BASEPWD=$(basename "$PWD")
      if [[ $SSH_TTY ]]
      then
        echo -ne "\033]0; ????️ $BASEPWD @ $HOSTNAME $cmd\a" < /dev/null
      else
        echo -ne "\033]0; ???? $BASEPWD $cmd\a" < /dev/null
      fi
    fi

  }
  starship_precmd_user_func="set_win_title"
  eval "$(starship init bash)"
  trap "$(trap -p DEBUG |  awk -F"'" '{print $2}');set_win_title \${BASH_COMMAND}" DEBUG

Note this differs from the Custom pre-prompt and pre-execution Commands in Bash instructions in that the trap is set after starship init. Which I have noted in a bug.

平生欢 2025-01-20 21:20:54

更新:我之前的回答(在本文末尾)在标题栏中显示了上一个命令。

忽略我之前答案中的所有内容并从头开始:

trap 'echo -ne "\033]0;${PWD}: (${BASH_COMMAND})\007"' DEBUG

在命令提示符下运行以下命令:

$ sleep 10

窗口标题栏更改为 /my/current/directory: (sleep 10) while sleep 10 正在运行。

运行以下任一命令:

$ sleep 1; sleep 2; sleep 3
$ { sleep 1; sleep2; sleep 3; }

标题栏会随着调用每个 sleep 命令而发生变化。

运行此命令:

$ ( sleep 1; sleep 2; sleep 3 )

标题栏不会更改(trap 不适用于子流程调用)。

最后一个:

$ echo $(sleep 3; echo abc)

标题栏显示 (echo $sleep 3; echo abc))


上一个答案

添加到此答案

store_command() {
  declare -g last_command current_command
  last_command=$current_command
  current_command=$BASH_COMMAND
  return 0
}
trap store_command DEBUG

PROMPT_COMMAND='echo -ne "\033]0;${PWD}: (${last_command})\007"'

附加阅读材料:trap / DEBUG:

UPDATE: my previous answer (at end of this post) displays the previous command in the title bar.

Ignoring everything from my previous answer and starting from scratch:

trap 'echo -ne "\033]0;${PWD}: (${BASH_COMMAND})\007"' DEBUG

Running the following at the command prompt:

$ sleep 10

The window title bar changes to /my/current/directory: (sleep 10) while the sleep 10 is running.

Running either of these:

$ sleep 1; sleep 2; sleep 3
$ { sleep 1; sleep2; sleep 3; }

The title bar changes as each sleep command is invoked.

Running this:

$ ( sleep 1; sleep 2; sleep 3 )

The title bar does not change (the trap does not apply within a subprocess call).

One last one:

$ echo $(sleep 3; echo abc)

The title bar displays (echo $sleep 3; echo abc)).


previous answer

Adding to this answer:

store_command() {
  declare -g last_command current_command
  last_command=$current_command
  current_command=$BASH_COMMAND
  return 0
}
trap store_command DEBUG

PROMPT_COMMAND='echo -ne "\033]0;${PWD}: (${last_command})\007"'

Additional reading materials re: trap / DEBUG:

罪歌 2025-01-20 21:20:54

对于Linux操作系统bashrc文件中添加以下函数

以下步骤

  1. 打开bashrc文件

vi ~/.bashrc

  1. 在bashrc文件中编写函数

    函数设置标题() {
       如果 [[ -z "$ORIG" ]];然后
         原始=$PS1
       菲
       TITLE="\[\e]2;$*\a\]"
       PS1=${原件}${标题}
     }

在此处输入图像描述

  1. 保存文件

源~/.bashrc

  1. 调用函数

设置标题“tab1”

在此处输入图像描述

For Linux OS Adding following function in bashrc file

Following Steps

  1. Open bashrc file

vi ~/.bashrc

  1. Write a function in bashrc file

    function set-title() {
       if [[ -z "$ORIG" ]]; then
         ORIG=$PS1
       fi
       TITLE="\[\e]2;$*\a\]"
       PS1=${ORIG}${TITLE}
     }

enter image description here

  1. save the file

source ~/.bashrc

  1. call function

set-title "tab1"

enter image description here

遗弃M 2025-01-20 21:20:54

您可以将设置窗口标题与设置提示结合起来。

下面是一个使用 PROMPT_COMMAND< 的示例/代码>:

tputps () {
    echo -n '\['
    tput "$@"
    echo -n '\]'
}

prompt_builder () {
    # Window title - operating system command (OSC) ESC + ]
    echo -ne '\033]0;'"${USER}@${HOSTNAME}:$(dirs)"'\a' >&2

    # username, green
    tputps setaf 2
    echo -n '\u'

    # directory, orange
    tputps setaf 208
    echo -n ' \w'
    tputps sgr0 0
}

prompt_cmd () {
    PS1="$(prompt_builder) \$ "
}

export PROMPT_COMMAND=prompt_cmd

You can combine setting the window title with setting the prompt.

Here's an example using s PROMPT_COMMAND:

tputps () {
    echo -n '\['
    tput "$@"
    echo -n '\]'
}

prompt_builder () {
    # Window title - operating system command (OSC) ESC + ]
    echo -ne '\033]0;'"${USER}@${HOSTNAME}:$(dirs)"'\a' >&2

    # username, green
    tputps setaf 2
    echo -n '\u'

    # directory, orange
    tputps setaf 208
    echo -n ' \w'
    tputps sgr0 0
}

prompt_cmd () {
    PS1="$(prompt_builder) \$ "
}

export PROMPT_COMMAND=prompt_cmd
晨曦慕雪 2025-01-20 21:20:54

不幸的是,我无法在任何地方找到有关避免使用原始转义序列来设置终端模拟器窗口标题的说明。使用晦涩的原始转义序列并不好,这也是 terminfo 数据库 被淘汰的原因之一创建,所以我有动力详细研究它,在我的 ~/.bashrc 中正确设置窗口标题,并最终写下这个答案。

首先,这是我的 ~/.bashrc 的摘录,其中显示了我实现的用于设置窗口标题的 bash 代码,同时不使用原始转义序列:

if [[ "${TERM}" != 'linux' ]]; then
        # Force the terminal type, to work around GUI terminal
        # emulators that set $TERM wrongly to a type that doesn't
        # support status line, e.g. "xterm-256color"

        SL_TERM='xterm-pcolor'
        SL_START="$(TERM=${SL_TERM}; tput tsl)"
        SL_END="$(TERM=${SL_TERM}; tput fsl)"

        SL_CMD='${USER}@${HOSTNAME%%.*} ${PWD/#${HOME}/\~}'
        SL_CMD+='$(STATUS=${?}; [[ ${STATUS} != 0 ]] && echo -n " [ERROR: ${STATUS}]")'

        PROMPT_COMMAND="echo -n \"${SL_START}${SL_CMD}${SL_END}\""
        unset SL_TERM SL_START SL_END SL_CMD
else
        unset PROMPT_COMMAND
fi

这里的关键是使用 tput(1) 实用程序使用 terminfo(5) 数据库,描述各种功能终端和终端模拟器。正如您在上面的 bash 代码中的注释中看到的,某些终端模拟器实际上行为有点不正常,但这可以很容易地解决。

我们感兴趣的两个终端功能是 tslto_status_line,移至状态行,第 1 列)和 fslfrom_status_line,从状态行返回)。这两个功能实际上分别生成原始转义序列 \033]0;\007,您可以在任何地方找到它们。

显然,Linux 虚拟控制台没有状态行功能,因此上面的代码配置了当 shell 运行时不更新状态行。使用 infocmp(1M),例如通过运行 infocmp -I linuxinfocmp -I xterm-256colorinfocmp -I xterm-pcolor

这里还有一些版本的 XTerm 控制序列参考,它们很难找到,按照可读性的降序排列:2023 版本 (HTML), 1994 版本 (PDF),以及 2005 版本 (HTML)。

我希望这将有助于揭开整个事情的神秘面纱。

Unfortunately, I was unable to find anywhere some instructions about avoiding the use of raw escape sequences to set the title of a terminal emulator window. Using obscure raw escape sequences isn't great and is one of the reasons why the terminfo database was created, so I got motivated to research it all in detail, to implement setting the window title properly in my ~/.bashrc, and to finally write this answer.

First, here's an excerpt from my ~/.bashrc, which shows the bash code I implemented to set the window title, while using no raw escape sequences:

if [[ "${TERM}" != 'linux' ]]; then
        # Force the terminal type, to work around GUI terminal
        # emulators that set $TERM wrongly to a type that doesn't
        # support status line, e.g. "xterm-256color"

        SL_TERM='xterm-pcolor'
        SL_START="$(TERM=${SL_TERM}; tput tsl)"
        SL_END="$(TERM=${SL_TERM}; tput fsl)"

        SL_CMD='${USER}@${HOSTNAME%%.*} ${PWD/#${HOME}/\~}'
        SL_CMD+='$(STATUS=${?}; [[ ${STATUS} != 0 ]] && echo -n " [ERROR: ${STATUS}]")'

        PROMPT_COMMAND="echo -n \"${SL_START}${SL_CMD}${SL_END}\""
        unset SL_TERM SL_START SL_END SL_CMD
else
        unset PROMPT_COMMAND
fi

The key here is to use the tput(1) utility to generate the required escape sequences, using the terminfo(5) database that describes the capabilities of various terminals and terminal emulators. As you can see in the comment in the bash code above, some terminal emulators actually misbehave a bit, but that can be worked around rather easily.

The two terminal capabilities we're interested in are tsl (to_status_line, move to status line, column #1) and fsl (from_status_line, return from status line). These two capabilities actually produce the raw escape sequences \033]0; and \007, respectively, which you can find mentioned everywhere.

Obviously, the Linux virtual console has no status line capabilities, so the code above configures no status line updates when the shell is running there. The capabilities of each terminal type can be checked rather easily by using infocmp(1M), for example by running infocmp -I linux, infocmp -I xterm-256color, or infocmp -I xterm-pcolor.

Here are also a few versions of the XTerm Control Sequences reference, which are rather hard to locate, listed in the descending order of their readability: 2023 version (HTML), 1994 version (PDF), and 2005 version (HTML).

I hope this will help with demystifying the whole thing a bit.

囍笑 2025-01-20 21:20:54

我最近将终端模拟器从 Konsole 切换到 Alacritty,我想在 Alacritty 中模拟 Konsole 的标题栏行为。我发现将以下几行添加到我的 ~/.bashrc 中效果非常好。如果您使用的是不同的终端模拟器,请替换您终端的 if 语句中的 "${TERM}" == "alacritty"

if [[ "${TERM}" == "alacritty" ]]; then
    trap 'printf "\033]0;%s : %s — Alacritty\007" "${PWD/#$HOME/\~}" "${BASH_COMMAND%% *}"' DEBUG
    PROMPT_COMMAND='printf "\033]0;%s : bash — Alacritty\007" "${PWD/#$HOME/\~}"'
fi

在上述方法中,请注意

  • ${BASH_COMMAND%% *} 将命令截断为正在运行的程序。如果您希望显示完整命令,可以使用 ${BASH_COMMAND} 代替。
  • printf 语句中使用 %s 可确保正确处理字符串,以避免意外输出。
  • trap 命令使用当前运行命令的名称动态更新终端标题。例如,在主目录中运行 sleep 10 会在标题栏中显示 ~ : sleep — Alacritty
  • 当没有程序运行时,标题默认返回到 ~ : bash — Alacritty,如 PROMPT_COMMAND 所定义。

I recently switched my terminal emulator from Konsole to Alacritty and I wanted to simulate Konsole's title bar behavior in Alacritty. I found that adding the following lines to my ~/.bashrc works quite well. If you're using a different terminal emulator, please replace "${TERM}" == "alacritty" in the if statement for your terminal.

if [[ "${TERM}" == "alacritty" ]]; then
    trap 'printf "\033]0;%s : %s — Alacritty\007" "${PWD/#$HOME/\~}" "${BASH_COMMAND%% *}"' DEBUG
    PROMPT_COMMAND='printf "\033]0;%s : bash — Alacritty\007" "${PWD/#$HOME/\~}"'
fi

In above approach, note that

  • ${BASH_COMMAND%% *} truncates the command to the program being run. If you prefer to display the full command, you can use ${BASH_COMMAND} instead.
  • Using %s in the printf statements ensures proper handling of the strings to avoids unexpected output.
  • The trap command dynamically updates the terminal title with the name of the currently running command. For example, running sleep 10 in your home directory gives ~ : sleep — Alacritty in title bar.
  • When no program is running, the title defaults back to ~ : bash — Alacritty, as defined by PROMPT_COMMAND.
岁月蹉跎了容颜 2025-01-20 21:20:54

我能想到的更改终端标题的最简单方法是在 shell 脚本中使用 echo

echo "\033]0;Your title \007"

并使用新标题名称更改打开新选项卡是

meta-terminal--tab-t"Your title" 

The easiest way to change the title of the terminal I could think of is to use echo in shell script

echo "\033]0;Your title \007"

And to change open a new tab with new title name is

meta-terminal--tab-t"Your title" 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文