Tuesday, February 09, 2021

Bash-ism to Display Last Command in xterm Title Bar

I got frustrated at the lack of support for displaying the last command entered in the xterm title bar when I bounced around from host to host, so I came up with a bash-ism to remedy the problem.

Add these to your .bashrc file on any hosts that this matters to you. I suspect there is a cleaner implementation but all of the command escaping was getting too complicated, so I broke it up into two separate functions.

This only works with versions of bash with PS0 support (bash 4.4 or higher) and I have only tested it using the macOS Terminal.app. It seems to work exactly as expected in screen sessions too, which is a nice bonus.

Fixes welcomed and appreciated, particularly those that make this work on earlier versions of bash. Just leave a comment or @ me on twitter.

 

settitle() {
    [[ -z $1 ]] && return
    case ${TERM} in
        xterm*) echo -n -e "\033]0;$1\007";;
    esac
}

lastcmd() {
    echo $(fc -l -1 -1 | sed -e 's/\s*[0-9]*\s*//');
}

export PS0='$(settitle "$(lastcmd)")'

 

Note: macOS does not deliver with bash 4.4 (yet?), so you should make sure to leave the "Active process name" setting checked in your Terminal.app to get this information locally. These are the settings that I am using.






No comments: