Bash – pass all arguments from one script to another

When writing a wrapper bash script, we often need to pass all arguments passed to the wrapper scrip to another script. Here is quick bash code snippet to pass all arguments to another script:

Passing all arguments in bash using $@

Here is sample code to print whatever arguments are passed to it.

#!/bin/bash
echo "Total $# arguments passed to me are: $*"

The code which passes argument using $@

#!/bin/bash
./child.sh $@

To test above bash script we can run this on command line:

./pass_all.sh a b c

And here is the outcome:

Total 3 arguments passed to me are: a b c
Env: GNU bash, version 4.3.11

Passing arguments after removing first arg

In case you want to consume one argument before passing to second script, then you can use shift as shown below:

#!/bin/bash
#remove first argument
FIRST=$1
shift
echo "Removed first arg: $FIRST"
./child.sh $@

To test above bash script we can run this code on command line:

./pass_all_after_shift.sh a b c

And here is the outcome:

Removed first arg: a
Total 2 arguments passed to me are: b c
Env: GNU bash, version 4.3.11

Additional notes on $@ and $*

  1. Note that $@ can also be used as "$@"
  2. An alternate approach is to use $*. It does not work when used within quotes (“$*”) though. So its always better to use $@.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments