I am trying to write a shell script which has a part where I have to use some kind of loop to execute some commands if condition satisfy. I want to understand what is the best way to approach this problem.
Lets say there are 3 flags
#export flag1=1
#export flag2=1
#export flag3=1
These are commented in the beginning. While running the script, I want to enable these flags one after the other.
So for that I have written a if else loop in such way.
if [[ -n ${flag1} ]]; then
#some commands
elif [[ -n "${flag2}" ]]; then
#some commands
elif [[ -n ${flag3} ]]; then
#some commands
else
#some commands
fi
But, when I enable flag1 it goes to else loop and it's giving different result than expected.
What's the best way to approach this issue?
Should I use case instead of if else loop ?
elif
dofi; if
?giving different result than expected.
what exactly is expected? There are 3 flags, which gives 2³ = 8 combinations of flags beeing set and unset. Please specify what exactly is expected for each of combinations of flags.if else loop
A "loop" is a repeating part of code, it executes multiple times as in "in a loop". The expressions insideif
execute once. They are usually called a "body", like "if body" or "else body", and they both execute once.echo 1 2 3 4
to each body and test it. I think the best way to deal with your "doubt" is to proof what actually happens.if … else
block is not a loop, i.e. code is not executed repeatedly, just once and on condition. For a loop (that may repeat executing a block of code) usefor
orwhile
. If needed, both structures can also be nested inside each other. As for your core issue, however, you only seem to need conditional blocks, i.e.if
orcase
. It looks like you want to test the flags independently, so either use oneif
per condition (don't branch toelse
), or use a singlecase
block with fall-throughs (;&
or;;&
instead of;;
).