Last active
October 28, 2023 14:20
-
-
Save stbuehler/4672115 to your computer and use it in GitHub Desktop.
ssh wrapper to quote command and arguments for remote end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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