1

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

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

4 Comments

what if I want to assign the flag value to ${i}FLAG inside the for loop for suppose ```${i}FLAG=`cat flags.properties |grep -i FIRST | cut -d "=" -f2````
I think that followup question should be asked as a new StackOverflow question, but, you could probably make use of eval to solve that. e.g. eval "${i}FLAG=1" would force FIRSTFLAG, SECONDFLAG or THIRDFLAG to become equal to 1.
Actually, it appears you can just go (( ${i}FLAG=1 )).
Yeah, I just realised that. Thank you.

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.