Variable inside another variable in bash script

I am trying to delete some files with loop. But can't figure out the way of doing it. Here's what I am trying to do:

#!/bin/bash
dir1=/path/to/file
dir2=/path/to/file
dir3=/path/to/file
for i in 1 2 3
do rm ${dir$i}
done
1

2 Answers

This is possible with eval, but I'd strongly advice not to use that!

Use an array instead:

dirs=(
"/path/to/file1"
"/path/to/file2"
"/path/to/file3"
)
for i in 0 1 2
do rm "${dirs[$i]}"
done
# OR simply loop all the array values:
for dir in "${dirs[@]}"
do rm "$dir"
done

Note, that arrays are 0-based.

5

You can do it in bash with indirection

 If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new pa‐ rameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion.

but it requires an intermediate variable ex. given:

dir1=/path/to/file1
dir2=/path/to/file2
dir3=/path/to/file3

then

$ for i in 1 2 3; do d=dir$i; echo rm "${!d}"; done
rm /path/to/file1
rm /path/to/file2
rm /path/to/file3

You could eliminate the intermediate variable by looping over strings dir1 dir2 dir3 using brace expansion:

for d in dir{1..3}; do echo rm "${!d}"; done

The same feature is available in zsh using the P modifier:

% for i in 1 2 3; do d=dir$i; echo rm ${(P)d}; done

See Use a variable reference "inside" another variable

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like