Skip to content

Instantly share code, notes, and snippets.

@stbuehler
Last active October 28, 2023 14:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stbuehler/4672115 to your computer and use it in GitHub Desktop.
Save stbuehler/4672115 to your computer and use it in GitHub Desktop.
ssh wrapper to quote command and arguments for remote end
#!/bin/bash
# quote command in ssh call to prevent remote side from expanding any arguments
# uses bash printf %q for quoting - no idea how compatible this is with other shells.
# http://stackoverflow.com/questions/6592376/prevent-ssh-from-breaking-up-shell-script-parameters
sshargs=()
while (( $# > 0 )); do
case "$1" in
-[1246AaCfgKkMNnqsTtVvXxYy])
# simple argument
sshargs+=("$1")
shift
;;
-[bcDeFIiJLlmOopRSWw])
# argument with parameter
sshargs+=("$1")
shift
if (( $# == 0 )); then
echo "missing second part of long argument" >&2
exit 99
fi
sshargs+=("$1")
shift
;;
-[bcDeFIiJLlmOopRSWw]*)
# argument with parameter appended without space
sshargs+=("$1")
shift
;;
--)
# end of arguments
sshargs+=("$1")
shift
break
;;
-*)
echo "unrecognized argument: '$1'" >&2
exit 99
;;
*)
# end of arguments
break
;;
esac
done
# user@host
sshargs+=("$1")
shift
# command - quote
if (( $# > 0 )); then
# no need to handle passed command as an array - ssh will merge it anyway.
# use bash @Q parameter transformation to quote $@:
sshargs+=("${@@Q}")
fi
exec ssh "${sshargs[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment