kingdj
kingdj

Reputation: 13

How to call variables in a for loop as both the variable name and the variable value

Im relatively new to scripting in Linux (more used to using R) but I am trrying to excecute a script where I set a number of variables as file paths which I can then subsequently call in a for loop So I can call both the variable name and the variable values separately across the script.

For example I will call the variable value (as in the file path) for the arguments of the command, but for the output of the command I will call the variable name to write the output. I have tried to achieve this using the curly brackets below. Will this work???

Any help would be greatly appreciated!

#Generate variables with path directories
C1=/path/file1
C2=/path/file2
C3=/path/file3
C4=/path/file4
L1=/path/file1
L2=/path/file2
L3=/path/file3

#Loop through each instance of C for each instance of L (to create L*C number of outputs)
for Cid in C1, C2, C3, C4,
do for Lid in L1, L2, L3,
do
commandA -arg1 $${Cid} -arg2 $${Lid} -output /path/file${Cid}${Lid}
done
done

Upvotes: 1

Views: 65

Answers (1)

PesaThe
PesaThe

Reputation: 7499

This is a job for associative array declared with declare -A:

#!/usr/bin/env bash

declare -A arr=(
[C1]=/path/file1
[C2]=/path/file2
[L1]=/path/file1
[L2]=/path/file2
)

for index in "${!arr[@]}"; do
    echo "$index:${arr[$index]}"
done
  • ${!arr[@]}: all indexes of the array (C1, C2, ... )
  • ${arr[$index]}: array element corresponding to the given index (/path/file1, ... )

If you want to stick to regular variables, you can use variable indirection:

C1=/path/file1
C2=/path/file2
L1=/path/file1
L2=/path/file2

for var in C1 C2 L1 L2; do
    echo "$var:${!var}"
done

${!parameter}

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

Upvotes: 1

Related Questions