Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elements of a bash array as separate command line arguments to python

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?

like image 608
Phanindra Avatar asked Mar 01 '26 07:03

Phanindra


1 Answers

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.

like image 133
Barmar Avatar answered Mar 04 '26 03:03

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!