#!/bin/bash
# http://www.infoworld.com/article/2893519/linux/perl-python-ruby-are-nice-bash-is-where-its-at.html
usage="Usage: $0 <ip address>"
if [ ! $1 ]; then
    echo $usage
    exit
fi
ip=$1
checkresult() {
    if [ $? -gt 0 ]; then
        echo "Problem encountered, aborting."
        ssh -O exit -S /tmp/ssh_mux_%h_%p_%r root@$ip >/dev/null 2>&1
        exit
    else
        echo "Completed."
    fi
}
# Start an ssh control session in the background with no command.
ssh -S /tmp/ssh_mux_%h_%p_%r -M -N -f -i ./id_dsa root@$ip
checkresult
echo "Doing something…"
ssh -S /tmp/ssh_mux_%h_%p_%r root@$ip 'do something here'
checkresult
echo "Doing something else…"
ssh -S /tmp/ssh_mux_%h_%p_%r root@$ip 'do something else here'
checkresult
# Kill persistent ssh session
echo "Exiting…"
ssh -O exit -S /tmp/ssh_mux_%h_%p_%r root@$ip >/dev/null 2>&1
checkresult


syntax highlighted by Code2HTML, v. 0.9.1