0

I'd like to use variables inside the for loop in shell.

My current code:

VAA="1st_first"
VAB="2nd_second"
VAC="3rd_third"

for i in VAA VAB VAC; do if [[ "${i}" =~ ^[A-Za-z]*$ ]]; then echo "$i variable is a word" else echo "$i variable is not a word" fi done

The expected result would be checking the $VAR1, $VAR2, and $VAR3 variables, then print that it's a word.

The current output is:

VAA variable is a word
VAB variable is a word
VAC variable is a word

It's not correct, because the "$VAA" is contains a number.

How can I use variables from outside of for loop?

Feriman
  • 969
  • 1
    Or, depending on what exactly you're doing, use for i in "$VAA" "$VAB" "$VAC"; do – muru Dec 01 '22 at 10:46

2 Answers2

1

I usually solve thing like this with associative arrays. But I do not know if this is an efficient solution. But this does not guarantee the original order as it looks in the output

#!/bin/bash

declare -A varCheck varCheck=( [VAA]="stfirst" [VAB]="2nd_second" [VAC]="3rd_third" )

for var in ${!varCheck[@]}; do if [[ "${varCheck[$var]}" =~ ^[A-Za-z]*$ ]]; then echo "${var} variable is a word" else echo "${var} variable is not a word" fi done

Output:

VAB variable is not a word
VAC variable is not a word
VAA variable is a word
lw0v0wl
  • 126
1

Use variable indirection

$i will show the word of i iterator.

${!i} will show the variable's content. this is a variable indirection.

Therefore to check the content, you need to use ${!i}

The solution is :

VAA="1st_first"
VAB="2nd_second"
VAC="3rd_third"

for i in VAA VAB VAC; do if [[ "${!i}" =~ ^[A-Za-z]*$ ]]; then echo "$i variable is a word" else echo "$i variable is not a word" fi done

The result :

VAA variable is not a word
VAB variable is not a word
VAC variable is not a word