ssh's ControlMaster with zsh

December 31, 2008

linux

You are using the ControlMaster feature of ssh and you are having problems remembering which shell is the master?

That’s why I’ve made zsh display this in the prompt. You get a m@ when a connection is a master connection and an @ if it is a slave.

setting up

The check if we are a master works by creating a file which has $SSH_CLIENT as the name, as the following snippet shows.

# ssh stuff
# check if we are the master or a slave connection
# this must be sourced before .zprompt is

# print @-sign before the hostname if we got into this host via SSH
if [ -z $SSH_TTY ]; then
ZSSH=
else
if [[ ! -e ~/.ssh/${SSH_CLIENT// /_} ]]; then
    # file does not exist, we are a master
    touch ~/.ssh/${SSH_CLIENT// /_}
    ZSSH="m@"
else
    # slave connection
    ZSSH="@"
fi
fi

tearing down

Make zsh remove the file when it exits.

TRAPEXIT() {
echo $PWD > ~/.zpwd
# $ZSSH has @ for slaves and M@ for masters
[[ $ZSSH == "m@" ]] && rm ~/.ssh/${SSH_CLIENT// /_}
}

You can now use $ZSSH in your prompt.

Zsh