How to make sure that the title of a Terminal tab/window is identical to the command I typed

bashcommand lineterminal

I noticed that for aliases etc the title of a Terminal tab/window often isn't the same as the command I typed. This is sometimes confusing, especially for long-running processes with similar names.

So how can I configure bash/Terminal in a way which ensures that the window title always reflects the command as typed?

Examples:

  • When I type python -m SimpleHTTPServer and press Return in a Terminal window, the tab of that Terminal window should show "python -m SimpleHTTPServer" immediately.

  • When I type flushdns, which is my alias for sudo killall -HUP mDNSResponder;sudo killall mDNSResponderHelper;sudo dscacheutil -flushcache and press Return in a Terminal window, the tab of that Terminal window should show "flushdns" immediately.

What I tried:

I tried modifying PS4 to run a command. This works, however it also prints a lot of other garbage, like getting the current git branch and other commands I put in my PS1. If there's a way for PS4 to only run scripts and not output anything (not even line breaks) I'm fine with that too as a solution.

I also tried the various options under Preferences > Profiles > Tab, but it does not allow showing the literal command I just entered.

Best Answer

macOS Catalina (10.15) now uses Zsh, which makes this really easy.

Show the currently running / last run command by disabling auto_title and adding a preexec hook:

# File: ~/.zshrc

DISABLE_AUTO_TITLE="true"

preexec() {
    printf "\e]1;${1}\a"
}