Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - How to pass arguments to a script that is read via redirected standard input

Tags:

bash

ssh

I would like to expand a little more on "Bash - How to pass arguments to a script that is read via standard input" post.

I would like to create a script that takes standard input and runs it remotely while passing arguments to it.

Simplified contents of the script that I'm building:

ssh server_name bash <&0

How do I take the following method of accepting arguments and apply it to my script?

cat script.sh | bash /dev/stdin arguments

Maybe I am doing this incorrectly, please provide alternate solutions as well.

like image 888
dabest1 Avatar asked Dec 16 '11 01:12

dabest1


People also ask

Can you pass in an argument to a bash script?

We can pass parameters just after the name of the script while running the bash interpreter command. You can pass parameters or arguments to the file.

How do you access arguments from within the script write the script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.


2 Answers

Try this:

cat script.sh | ssh some_server bash -s - <arguments>
like image 81
ccarton Avatar answered Sep 26 '22 00:09

ccarton


ssh shouldn't make a difference:

$ cat do_x 
#!/bin/sh

arg1=$1
arg2=$2
all_cmdline=$*
read arg2_from_stdin

echo "arg1: ${arg1}"
echo "arg2: ${arg2}"
echo "all_cmdline: ${all_cmdline}"
echo "arg2_from_stdin: ${arg2_from_stdin}"

$ echo 'a b c' > some_file
$ ./do_x 1 2 3 4 5 < some_file 
arg1: 1
arg2: 2
all_cmdline: 1 2 3 4 5
arg2_from_stdin: a b c
$ ssh some-server do_x 1 2 3 4 5 < some_file
arg1: 1
arg2: 2
all_cmdline: 1 2 3 4 5
arg2_from_stdin: a b c
like image 44
Brian Cain Avatar answered Sep 22 '22 00:09

Brian Cain