How to run a script when a title is set to a terminal tab

gnome-terminal

During my day-to-day work, I keep many terminal tabs. So to identify those, I set titles

Terminal Tab > Set Title

e.g.
IRC, API Codebase, API Logs, Server1, etc

What I want to do is do something in the tab based on the title of the tab.
e.g.

  1. When I set "API Codebase", It should go to my codebase and activate appropriate python virtual environment
  2. When I set "IRC", It should run irssi
  3. When I set "Server1", It should run ssh command to connect to the server

and so on.

How can this be done?

Best Answer

I would do this slightly differently. Instead of manually setting the tab's title, create a function that both sets the title and runs the desired command. Add this function (adapted from here) to your ~/.bashrc (assuming you're using bash):

function set-title() {
  if [[ -z "$ORIG" ]]; then
    ORIG=$PS1
  fi
  TITLE="\[\e]2;$@\a\]"

  ## Do different things depending on the string passed
  case "$@" in
        "API Codebase")
            echo cd ~/codebase
            echo python ...
            ;;
        "IRC")
            echo irssi
            ;;
        "Server1")
            echo ssh server1
            ;;
  esac
  PS1="${ORIG}${TITLE}"
}
Related Question