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.

2
  • Works fine when I test it? Commented Jul 14, 2017 at 15:23
  • 1
    Give shellcheck a try. It automatically points out this issue. Commented Jul 14, 2017 at 15:27

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use $@, and quote it.

#!/bin/bash

python "$@"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.