Reputation: 17154
I need to check which of the condition failed. Is there a better way of doing this? How can I refactor the code with less lines of code? Maybe a one liner if/else condition?
flag1=0
flag2=0
flag3=0
flag4=0
success=0
FAIL=""
if (( 2==2 ))
then
flag1=1
fi
# check if anything is 0
if (( $flag1==1 ))
then
FAIL="flag1"
elif (( $flag2==1 ))
then
FAIL="flag2"
elif (( $flag3==1 ))
then
FAIL="flag3"
elif (( $flag4==1 ))
then
FAIL="flag4"
fi;
echo failed is $FAIL
Upvotes: 0
Views: 41
Reputation: 531165
You can iterate over the names of the flags and use indirect parameter expansion to test the value of each flag. Use break
to stop testing once a test succeeds.
FAIL=""
for f in flag1 flag2 flag3 flag4; do
(( ${!f:-1} == 1 )) && FAIL=$f && break
done
Upvotes: 4