The terminal window title could be changed by changing of the value of the variable $PS1 - the primary prompt string. [1] [2]. We could combine this solution with the idea of using the history command from the Dessert's answer.
Approach 1: Update the value of $PS1 automatically. (Update)
Add the following lines to the bottom of the file ~/.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
Then source ~/.bashrc or just open a new terminal and use the function in this way:
- Execute
rtitle to start changing the terminal window title automatically, based on the last executed command.
- Execute
rtitle once again to return to the default behaviour.
Approach 2: Update the value of $PS1 manually. (Initial answer)
Add the following lines to the bottom of the file ~/.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
Then source ~/.bashrc or just open a new terminal and use the function in this way:
set-title <something> will change the terminal window title to <something>.
set-title without argument will change the terminal window title to the previous command.
References and examples: