Skip to content

Instantly share code, notes, and snippets.

@tpope
Created May 9, 2015 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpope/5dc82a31d68e8268f23b to your computer and use it in GitHub Desktop.
Save tpope/5dc82a31d68e8268f23b to your computer and use it in GitHub Desktop.
SSH to Git remotes
#!/usr/bin/env bash
# SSH to the user and host given by a Git remote and chdir to the repo path.
# The first argument is the remote name. All other arguments are passed to
# SSH, with some fudging to run a login shell if no command is given.
# Use git ssh -d to see the exact SSH command.
# Copyright (c) Tim Pope. Distributed under the MIT License.
set -e
. "$(git --exec-path)/git-parse-remote"
if [ "x$1" = x-d ]; then
debug=1
shift
fi
case "$1" in
[a-z]*)
remote="$1"
shift
;;
*)
remote=$(get_default_remote)
esac
case "$remote" in
*[:/]*)
url="$remote"
;;
*)
url=$(git config --get remote.$remote.url)
;;
esac
base=$(echo "$url"|sed -e 's,^[a-z]*://,,')
userhost=$(echo $base|sed -e 's/[:/].*//')
dir=$(echo $base|sed -e 's/^[^:/]*[:/]//')
if [ -z "$userhost" -o -z "$dir" ]; then
echo "Invalid remote $remote" >&2
exit 1
fi
ssh_args=()
while [ "$#" -gt 0 ]; do
case "$1" in
-*[1246AaCfgKkMNnqsTtVvXxYy])
ssh_args+=("$1")
shift
;;
-*[bcDEeFIiLlmOopQRSWw])
ssh_args+=("$1" "$2")
shift 2
;;
--)
shift
break
;;
*)
break
;;
esac
done
if [ "$#" -eq 0 ]; then
ssh_args+=(-t)
set -- exec '$SHELL' --login
fi
set -- "${SSH:-ssh}" $ssh_args "$userhost" cd "'$dir'" '||' 'exit 2;' "$@"
if [ -n "$debug" ]; then
echo "$@"
fi
exec "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment