OSX Terminal – Tab and window shortcuts

In a previous post, I shared a tip on Naming your Terminal tabs in OSX Lion. I’ve been meaning to share some additional shortcuts that I use day-to-day for opening new tabs and renaming them via the command line.

The workflow

We can rename tabs and windows as before:


# Rename tab
tabname "Funky Tab"

# Rename window
winname "Funky Window"

Or, leave out the name to base it the current directory:


# Rename tab to current directory name
tabname

# Rename window to current directory name
winname

…and to save typing, these are aliased as ‘tn’ and ‘tw’, so this will do the same:


# Rename tab to current directory name
tn

# Rename window to current directory name
wn

Now, for opening a new tab we have:


# Open new tab, cd into same directory as current tab and name it
tab

By default this will open a new tab, cd into the same directory as the current tab and name it based on it’s directory. You can optionally include a path:


# Open new tab, cd into specified directory and name it
tab ./path/to/directory

Of course, there is a lazy version of creating tabs too:


# Shortcut for 'tab'
t

The code

To get this functionality, just drop the following into your ~/.profile file:


function tabname {
  # Will use current dir name if called without arg.
  printf "\e]1;${1-$(basename `pwd`)}\a"
}
function winname {
  # Will use current dir name if called without arg.
  printf "\e]2;${1-$(basename `pwd`)}\a"
}
function tab {
  # Will cd into current dir if called without arg.
  osascript -e 'tell application "Terminal"' \
            -e 'tell application "System Events" to keystroke "t" using {command down}' \
            -e "do script \"cd `pwd` && cd ${1-.} && tabname && clear\" in front window" \
            -e 'end tell' > /dev/null
}
alias t='tab'
alias tn='tabname'
alias wn='winname'

See the Gist here.

Happy tabbing!

Naming your Terminal tabs in OSX Lion

If you find yourself in the Terminal app with a bunch of tabs open, the default name of “bash” isn’t very useful when navigating between them. You can change the tab name via the UI by right clicking the tab, then clicking “Inspect Tab” and changing the window or tab names but this is somewhat long winded.

Below are a couple of bash functions I have in my “.profile” file to make this easier:


function tabname {
  printf "\e]1;$1\a"
}

function winname {
  printf "\e]2;$1\a"
}

Now you can easily name your tabs or windows with the following:


# Rename tab
tabname "Funky Tab"

# Rename window
winname "Funky Window"

Thanks to Bubu and Chris Page on the SuperUser site for the right codes.