1

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.

s-m-e
  • 3,433
  • 2
  • 34
  • 71

2 Answers2

4

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You need to use $@, and quote it.

#!/bin/bash

python "$@"
chepner
  • 497,756
  • 71
  • 530
  • 681