How do I pass arbitrary arguments to a command executed over SSH? [duplicate]

为君一笑 提交于 2020-06-01 03:37:54

问题


Assume I have a script with the following contents located at ~/echo.sh on a remote server example.com:

#!/usr/bin/env bash
echo "Arg 1: $1"
echo "Arg 2: $2"
echo "Arg 3: $3"
echo "Arg 4: $4"

Now, on my local machine, I have another script, remote-echo.sh with the following contents:

#!/usr/bin/env bash
ssh example.com "~/echo.sh $*"

The idea is that a user should be able to run remote-echo.sh with any arguments and have those arguments be forwarded to ~/echo.sh on the remote server.

Unfortunately, this doesn't work:

$ ./remote-echo.sh "arg with space" "argwith\"quote" "arg3"
bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file

How do I fix this? I already tried using $@ instead of $*, but that didn't have any effect on the result at all.


回答1:


You need to ensure that all arguments embedded in the string passed to SSH are being properly escaped, so they don't get interpreted by the shell on the remote server. The simplest way to do this is using the %q format character for printf in Bash:

#!/usr/bin/env bash
ssh example.com "~/echo.sh $(printf "%q " "$@")"

According to the help information for printf in Bash:

In addition to the standard format specifications described in printf(1), printf interprets:

[...]

%q quote the argument in a way that can be reused as shell input

That should resolve the issue you see here, and ensure each argument is passed correctly to echo.sh.



来源:https://stackoverflow.com/questions/51547753/how-do-i-pass-arbitrary-arguments-to-a-command-executed-over-ssh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!