简体   繁体   中英

Pass a script with arguments via stdin as a string to the bash

Currently I'm having an issue to pass a script with arguments to the bash. The limitation is that I can pass them as a string (see $COMMAND)

ssh user@server 'bash -s' < "$COMMAND"

if my $COMMAND contains "foo.sh bar baz", I would get error no such file or directory: foo.sh bar baz

Additionally, I'm be able to set additional options to bash.

Thank you in advance!!!

The root problem is that < takes a filename to redirect from, not a filename and some arguments. Mixing the two together this way just won't work.

If I'm understanding right, you want to run a script that exists on the local computer, but have it execute (with the supplied arguments) on the remote computer. In that case, what you want to run is something like this:

ssh user@server 'bash -s bar baz' <"foo.sh"

Note that the arguments are passed in a completely different place than the script filename. If possible, I'd recommend never mixing the two; keep them in separate variables, and then use something like this:

ssh user@server "bash -s $scriptargs" <"$scriptfile"

From the sounds of the error, foo.sh doesn't exist on server, so it fails.

The simplest solution seems to be:

ssh user@server 'foo.sh bar baz' , provided "foo.sh" exists on the server.

If "foo.sh" doesn't/can't exist on the server, have you tried using here docs ? For example:

ssh user@server "cat > foo.sh && chmod u+x foo.sh && ./foo.sh bar baz" << "EOF"
`heredoc> #Put your contents of foo.sh here
`heredoc> #And put them here
`heredoc> echo "Argument 1: $1"
`heredoc> echo "Argument 2: $2"
`heredoc> EOF
user@server's password:
Argument 1: bar
Argument 2: baz

EDIT:

david@localhost ~ % bash -s < test.sh David Finder
Hello David
Hello Finder

Edit to my previous answer, the issue is due to the quoting of the input arguments thrown to Bash, as it sees the entire input as one file (it's looking for a file literally called "foo.sh bar baz", with spaces within.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM