Home > Software engineering >  Access variables using an external string.[SHELL script]
Access variables using an external string.[SHELL script]

Time:03-11

I currently have code as

if [[ "$FIRSTFLAG" == 1 ]] ; then
   all_comp =("FIRST")
fi
if [[ "$SECONDFLAG" == 1 ]] ; then
   all_comp =("SECOND")
fi
if [[ "$THIRDFLAG" == 1 ]] ; then
    all_comp =("THIRD")
fi

all_comp is just an array

So, im working on a solution to reduce the repetitive code
I know that we can use case here.
I wonder if there is a solution that can be done using array and for loop \
For example(I know its syntactically wrong)

names=("FIRST" "SECOND" "THIRD")
for i in $names[@]; do
   if [[ ${i}FLAG == 1 ]]; then     <- This line is the issue
      all_comp =("$i")
   fi
done

So please tell me if there is a solution for such code example

CodePudding user response:

You need to use indirect expansion by saving the constructed variable name, e.g. iflag=${i}FLAG, then you can use access the indirect expansion with ${!iflag}, e.g.

FIRSTFLAG=1
SECONDFLAG=0
THIRDFLAG=1
all_comp=()
names=("FIRST" "SECOND" "THIRD")
for i in ${names[@]}; do
   iflag=${i}FLAG
   if [[ ${!iflag} == 1 ]]; then
      all_comp =("$i")
   fi
done
echo ${all_comp[@]} # Outputs: FIRST THIRD

Oh another answer, you can make use of the arithmetic expansion operator (( )) i.e.

FIRSTFLAG=1
SECONDFLAG=0
THIRDFLAG=1
all_comp=()
names=("FIRST" "SECOND" "THIRD")
for i in ${names[@]}; do
   if (( ${i}FLAG == 1 )); then
      all_comp =("$i")
      (( ${i}FLAG = 99 ))
   fi
done
echo ${all_comp[@]} # FIRST THIRD
echo $FIRSTFLAG # 99
echo $SECONDFLAG # 0
echo $THIRDFLAG # 99

Reference:

  • Related