I have written an bash script foo.sh
#!/usr/bin/env bash
echo "starting the script";
I want to execute it in my remote server.
I tried ssh user@remote-addr < test.sh
and it worked.
After that I changed the test.sh file like this
#!/usr/bin/env bash
echo "starting the script";
echo $1;
now I want to pass a local parameter to execute with my script but when I type ssh user@remote-addr < test.sh testparam
it returns an error.
How can I pass parameters with my scripts?
Use the
-s
option, which forcesbash
(or any POSIX-compatible shell) to read its command from standard input, rather than from a file named by the first positional argument. All arguments are treated as parameters to the script instead.With
bash
orksh
as/bin/sh
If your remote
/bin/sh
is provided by bash or ksh, you can safely do the following with an untrusted argument list, such that even malicious names (like$(rm -rf $HOME).txt
) can be passed as arguments safely:...thereafter:
With Any POSIX-Compliant
/bin/sh
Note that the following still needs to be run in
bash
, but will work correctly when the system beingssh
'd into has a/bin/sh
that is POSIX-baseline, so long as the remote machine has bash installed.To be safe against sufficiently malicious argument data (attempting to take advantage of the non-POSIX compliant quoting used by
printf %q
in bash when nonprintable characters are present in the string being escaped) even with a/bin/sh
that is baseline-POSIX (such asdash
orash
), it gets a bit more interesting:Similarly invoked as: