0

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

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.