Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to bash when executing a script fetched by curl

I know how to execute remote Bash scripts like this:

curl http://example.com/script.sh | bash 

or

bash < <( curl http://example.com/script.sh ) 

which give the same result.

But what if I need to pass arguments to the bash script? It's possible when the script is saved locally:

./script.sh argument1 argument2 

I tried several possibilities like this one, without success:

bash < <( curl http://example.com/script.sh ) argument1 argument2 
like image 298
Daniel R Avatar asked Jan 10 '11 01:01

Daniel R


People also ask

How do you pass a parameter to a shell 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.

How in bash parameters are passed to a script?

Positional Parameters. Arguments passed to a script are processed in the same order in which they're sent. The indexing of the arguments starts at one, and the first argument can be accessed inside the script using $1. Similarly, the second argument can be accessed using $2, and so on.

How do you pass a variable to the curl in bash?

Let us say you want to pass shell variable $name in the data option -d of cURL command. There are two ways to do this. First is to put the whole argument in double quotes so that it is expandable but in this case, we need to escape the double quotes by adding backslash before them.


1 Answers

To improve on jinowolski's answer a bit, you should use:

curl http://example.com/script.sh | bash -s -- arg1 arg2 

Notice the two dashes (--) which are telling bash to not process anything following it as arguments to bash.

This way it will work with any kind of arguments, e.g.:

curl -L http://bootstrap.saltstack.org | bash -s -- -M -N stable 

This will of course work with any kind of input via stdin, not just curl, so you can confirm that it works with simple BASH script input via echo:

echo 'i=1; for a in $@; do echo "$i = $a"; i=$((i+1)); done' | \ bash -s -- -a1 -a2 -a3 --long some_text 

Will give you the output

1 = -a1 2 = -a2 3 = -a3 4 = --long 5 = some_text 
like image 56
Janne Enberg Avatar answered Sep 19 '22 06:09

Janne Enberg