Passing Arguments to a Script Invoked with Bash -C

Passing argument to bash -c shell script

curl -fsSL https://storage.googleapis.com/<Some_bucket>/rules.sh | bash -s param1 param2

Passing arguments to a script invoked with bash -c

You’re actually over-complicating things by using xargs with Bash’s -c option.

Download the script directly

You don’t need to clone the repository to run the script. Just download it directly:

curl -o gid https://raw.githubusercontent.com/jamesqo/gid/master/gid

Now that it’s downloaded as gid, you can run it as a Bash script, e.g.,

bash gid --help

You can also make the downloaded script executable in order to run it as a regular Unix script file (using its shebang, #!/bin/bash):

chmod +x gid
./gid --help

Use process substitution

If you wanted to run the script without actually saving it to a file, you could use Bash process substitution:

bash <(curl -sSL https://github.com/jamesqo/gid/raw/master/gid) --help

Including $@ to pass on all command line arguments when a shell script invokes itself with bash -c

bash -c should not be used as it cannot handle "3 4" easily:

#!/bin/bash
# If not in the right context, invoke script in right context and exit
if [ -z ${NESTED+x} ]; then
NESTED=true ./test.sh "$@"
exit
fi

echo "$1"
echo "$2"
echo "$3"

Passing multiple arguments through: `run bash -c ...`

Pass the argument normally but skip first one that is reserved in this context:

bash -c 'source src/some_script.sh && some_function "$@"' _ 'argument a' 'argument B' 'This is c' 'Andy'

The output:

variable_one=argument a
variable_two=argument B
variable_three=This is c
variable_four=Andy

Pass all args to a command called in a new shell using bash -c

Change file1.sh to this with different quoting:

#!/bin/bash
bash -c './file2.sh "$@"' - "$@"

- "$@" is passing hyphen to populate $0 and $@ is being passed in to populate all other positional parameters in bash -c command line.

You can also make it:

bash -c './file2.sh "$@"' "$0" "$@"

However there is no real need to use bash -c here and you can just use:

./file2.sh "$@"

How to pass arguments to a script invoked by source command?

Create a file test.sh with the following contents:

echo "I was given $# argument(s):"
printf "%s\n" "$@"

and then source it from an interactive shell session:

$ source ./test.sh a 'b c'
I was given 2 argument(s):
a
b c

so you access the arguments just like you would do in a regular bash script, with $@ or $1, $2, $3, etc.

For comparison, run it as a regular script:

$ bash ./test.sh a 'b c'
I was given 2 argument(s):
a
b c


Related Topics



Leave a reply



Submit