Bash – Pass command line parameters to a program inside the shell script

argumentsbashshellshell-script

As for ./script.sh arg1 [arg2 arg3 ...], the command line arguments arg1, arg2, … can be got by $1, $2, … But the number of arguments is NOT fixed.

In the shell script, I want to pass the arguments starting from arg2 to a program,

#/bin/bash
...
/path/to/a/program [I want to pass arg2 arg3 ... to the program]
...

How could I do it since there could be one or more arguments?

Best Answer

The usual way would be to save a copy of arg1 ("$1") and shift the parameters by one, so you can refer to the whole list as "$@":

#!/bin/sh
arg1="$1"
shift 1
/path/to/a/program "$@"

bash has some array support of course, but it is not needed for the question as posed.

If even arg1 is optional, you would check for it like this:

if [ $# != 0 ]
then
    arg1="$1"
    shift 1
fi