5

I needed to run a script over a bunch of files, which paths were assigned to train1, train2, ... , train20, and I thought 'why not make it automatic with 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 didn't work because train$i echoes train1's name, 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?

1
  • Oh, I could python something.py each_filename, but later I need to run some other scripts over the same files, that's why i put it on those variables Commented Jun 26, 2013 at 11:46

2 Answers 2

9

Use an array.

Bash does have variable indirection, so you can say

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

The ! introduces the indirection, so "get the value of the variable named by the value of 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 array's first index is at position zero, so:

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
Sign up to request clarification or add additional context in comments.

Comments

4

You can use 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 awfull way:

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

3 Comments

Thank you! Is this structure with square brackets some kind of dictionary?
@rafa It's the way get reference to array element. Some kind of short manual.
Simpler is for train in "${trains[@]}". Of course, the array variable name should be plural :)

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.