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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Phanindra
  • 137
  • 2
  • 4
  • 10

1 Answers1

3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 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"). – Phanindra Mar 18 '19 at 14:41
  • No, that would happen with `"${arr[*]}"`, but `[@]` is treated differently. – Barmar Mar 18 '19 at 15:02
  • @PhanindraRajaChava See https://stackoverflow.com/questions/3348443/a-confusion-about-array-versus-array-in-the-context-of-a-bash-comple – Barmar Mar 18 '19 at 15:04