Home > database >  How to change the terminal title to currently running process?
How to change the terminal title to currently running process?

Time:03-14

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.

CodePudding user response:

UPDATE: my previous answer (below) 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:

CodePudding user response:

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
  • Related