Search code examples
bashshellargumentsparameter-passingposix

How do I pass all command line arguments given to a bash script including string parameters as-is to a child process?


The following question is a variation of my problem:

Bash: Reading quoted/escaped arguments correctly from a string

I want to write a bash script (say 'something.sh') of the following kind ...

#!/bin/bash

python $*

... which passes all command line arguments as they were given to it directly to the child process. The above based on $* works for commands like ...

./something.sh --version

... just fine. However, it fails miserably for string arguments like for instance in this case ...

./something.sh -c "import os; print(os.name)"

... which results (in my example) in ...

python -c import

... cutting the string argument at the first space (naturally producing a Python syntax error).

I am looking for a generic solution, which can handle multiple arguments and string arguments for arbitrary programs called by the bash script.


Solution

  • Use this:

    python "$@"
    

    $@ and $* both expand to all the arguments that the script received, but when you use $@ and put it in double quotes, it automatically re-quotes everything so it works correctly.

    From the bash manual:

    Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ….

    See also Why does $@ work different from most other variables in bash?