user1008537
user1008537

Reputation:

Send string as arguments in bash

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 ?

Upvotes: 0

Views: 118

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295413

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.

Upvotes: 4

anubhava
anubhava

Reputation: 785156

Better to use BASH arrays:

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

Upvotes: 1

Related Questions