0

I have a string:

arguments="2 3 4"

And I want to send those arguments to a file file.py e.g.,

python file.py 2 3 4

How would I do that only using the string? The snippet below doesn't work (it just sends one argument, the entire string itself..).

python file.py $arguments ?
1
  • 3
    Are you sure your shell isn't zsh? That code should work exactly as given in bash (though it isn't good practice). Commented Jul 28, 2014 at 17:14

2 Answers 2

4

In bash (as opposed to zsh), that code should work as-given. That said, you might try ensuring that IFS contains a space:

IFS=' '

or, to reset it to defaults:

unset IFS

...before running that string. IFS determines which characters are used in shell-splitting, so if it doesn't contain a space, arguments separated by spaces won't be expanded.


Alternately -- preferably -- use an array:

arguments=( 2 3 4 )
python file.py "${arguments[@]}"

In that format, you can use arguments containing spaces:

arguments=(2 "thirty three" 4 )

...which will not work otherwise, for reasons documented in BashFAQ #050.

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

3 Comments

Unsetting IFS does not reset it to its default (which is <space><tab>< newline >), but does cause words to be split on spaces only.
@chepner, on doing a quick test (running unset IFS and expanding a variable with tab-delimited values), I'm getting behavior consistent with the $' \t\n' default being in use. I'm using 4.3.18(1)-release.
OK, I have too many versions of bash installed on my laptop. Looks like the shell's behavior when IFS is unset changed sometime between 3.2 and 4.1 (probably 4.0? the change log doesn't seem to acknowledge it).
1

Better to use BASH arrays:

arguments=(2 3 4)
python file.py "${arguments[@]}"

Comments

Your Answer

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