Iterating a variable name in a bash script

I needed to run the script through a bunch of files, which paths were assigned to train1 , train2 , ..., train20 , and I thought: "Why not do it automatically using a bash script? '.

So, I did something like:

 train1=path/to/first/file train2=path/to/second/file ... train20=path/to/third/file for i in {1..20} do python something.py train$i done 

which did not work because train$i displays the name train1 , but not its value.

So, I tried unsuccessfully things like $(train$i) or ${train$i} or ${!train$i} . Does anyone know how to catch the correct value of these variables?

+4
source share
2 answers

You can use an array:

 train[1]=path/to/first/file train[2]=path/to/second/file ... train[20]=path/to/third/file for i in {1..20} do python something.py ${train[$i]} done 

Or eval, but it's terrible:

 train1=path/to/first/file train2=path/to/second/file ... train20=path/to/third/file for i in {1..20} do eval "python something.py $train$i" done 
+4
source

Use an array.

Bash has variable indirection, so you can say

 for varname in train{1..20} do python something.py "${!varname}" done 

! introduces indirection, so "get the value of the variable called the value varname"

But use an array. You can make the definition very readable:

 trains=( path/to/first/file path/to/second/file ... path/to/third/file ) 

Note that this first index of the array is at position zero, therefore:

 for ((i=0; i<${#trains[@]}; i++)); do echo "train $i is ${trains[$i]}" done 

or

 for idx in "${!trains[@]}"; do echo "train $idx is ${trains[$idx]}" done 
+4
source

Source: https://habr.com/ru/post/1488270/


All Articles