3

I have a bash array which have paths in the form of string as its elements.

${arr[0]} = "path/to/json1"
${arr[1]} = "path/to/json2"
${arr[2]} = "path/to/json3"

and so on...

Now I want to pass all these elements as command line arguments to a python command within the same bash script at the same time

python3 script.py ${arr[0]} ${arr[1]} ${arr[2]}

But the problem is the number of elements in arr varies and is not fixed. So I can't hard code each element as a separate argument like above.

How can we pass all the elements of a bash array as command line arguments to python command?

1 Answer 1

4

Use ${arr[@]} to refer to the entire array.

python3 script.py "${arr[@]}"

This isn't specific to Python, it's how you pass all the array elements to any command.

You should also always quote shell variables unless you have a good reason not to.

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

3 Comments

Doesn't that concatenate all the paths in the array and pass it as a single string (like python3 scripy.py "path/to/json1 path/to/json2 path/to/json3")? I want to pass all the path elements separately (like python3 scripy.py "path/to/json1" "path/to/json2" "path/to/json3").
No, that would happen with "${arr[*]}", but [@] is treated differently.

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.