Bash - Update terminal title by running a second command

后端 未结 8 1501
Happy的楠姐
Happy的楠姐 2020-12-24 13:27

On my terminal in Ubuntu, I often run programs which keep running for a long time. And since there are a lot of these programs, I keep forgetting which terminal is for which

8条回答
  •  情话喂你
    2020-12-24 13:54

    I have some answers for you :) You're right that it shouldn't matter that you're using gnome-terminal, but it does matter what command shell you're using. This is a lot easier in zsh, but in what follows I'm going to assume you're using bash, and that it's a fairly recent version (> 3.1).

    First of all:

    Which environment variable would contain the current 'command'?

    There is an environment variable which has more-or-less what you want - $BASH_COMMAND. There's only one small hitch, which is that it will only show you the last command in a pipe. I'm not 100% sure what it will do with combinations of subshells, either :)

    So I was hoping to find a way to capture the command in bash and update the title after every command.

    I've been thinking about this, and now that I understand what you want to do, I realized the real problem is that you need to update the title before every command. This means that the $PROMPT_COMMAND and $PS1 environment variables are out as possible solutions, since they're only executed after the command returns.

    In bash, the only way I can think of to achieve what you want is to (ab)use the DEBUG SIGNAL. So here's a solution -- stick this at the end of your .bashrc:

    trap 'printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}"' DEBUG
    

    To get around the problem with pipes, I've been messing around with this:

    function settitle () {
        export PREV_COMMAND=${PREV_COMMAND}${@}
        printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}"
        export PREV_COMMAND=${PREV_COMMAND}' | '
    }
    
    export PROMPT_COMMAND=${PROMPT_COMMAND}';export PREV_COMMAND=""'
    
    trap 'settitle "$BASH_COMMAND"' DEBUG
    

    but I don't promise it's perfect!

提交回复
热议问题