public
Last active

CLI tool to create an SSH alias

  • Download Gist
sbm.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# SSH bookmark creator
sbm(){
if [ $# -lt 2 ]; then
echo "Usage: sbm <short> [<user>@]<hostname> [-p <port>]" >&2
return 1
fi
 
short=$1
arg=$2
 
if $(echo "$arg" | grep '@' >/dev/null); then
user=$(echo "$arg"|sed -e 's/@.*$//')
fi
 
host=$(echo "$arg"|sed -e 's/^.*@//')
 
if [ "$3" == "-p" ]; then
port=$4
fi
 
if $(grep -i "host $short" "$HOME/.ssh/config" > /dev/null); then
echo "Alias '$short' already exists" >&2
return 1
fi
 
if [ -z "$host" ]; then
echo "No hostname found" >&2
return 1
fi
 
echo >> "$HOME/.ssh/config"
echo "host $short" >> "$HOME/.ssh/config"
echo " hostname $host" >> "$HOME/.ssh/config"
[ ! -z "$user" ] && echo " user $user" >> "$HOME/.ssh/config"
[ ! -z "$port" ] && echo " port $port" >> "$HOME/.ssh/config"
 
echo "added alias '$short' for $host"
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.