2

I'm nearly done writing a script for an assignment, but am having some trouble thinking of how to do this final part.

My problem is within a while loop; it prints out the number based on the IF statements, the number entered will always be an even number.

The IFs aren't connected by else/elif because the number should be able to printed out if it applies to more than 1 of the statements.

I want to print $starting on every loop if it doesn't meet any of the IF conditions, but if it does I don't want to print it. Can anyone see how to do that?

while [[ $starting -lt $ending ]]; do
    if [ $((starting %7)) -eq 0 ] 
    then
    echo "$starting red"
    fi
    if [ $((starting % 11)) -eq 0 ]
    then
    echo "$starting green"
    fi
    if [ $((starting % 13)) -eq 0 ]
    then
    echo "$starting blue"
    fi
    starting=$((starting + 2))
done

2 Answers 2

3

Keep track of whether you've done what you want to do in a variable:

while [[ $starting -lt $ending ]]; do

handled=0

if [ $((starting %7)) -eq 0 ] 
then
echo "$starting red"
handled=1
fi
if [ $((starting % 11)) -eq 0 ]
then
echo "$starting green"
handled=1
fi
if [ $((starting % 13)) -eq 0 ]
then
echo "$starting blue"
handled=1
fi

if ! (( handled ))
then 
  echo "$starting didn't match anything"
fi

starting=$((starting + 2))
done
2

Add another if at the end that checks if none of the previous if statements are true. if !(starting%7==0 or starting%11==0 or starting%13==0) => echo starting

1
  • Thanks! This worked, I added in: if [ $((starting % 7)) -ne 0 ] && [ $((starting % 11)) -ne 0 ] && [ $((starting % 13)) -ne 0 ] Mar 28, 2014 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.