0

I have written a short Bash Script:

   for j in 0 1 2 3 4 5
   do
       for (( i=$j; i <= 5; i++ ));
       do
           if [ $(($(($i - $j)) > 1)) ]; then
               echo "True" 
           else
               echo  "False"
           fi
       done
   done

I expect this script to output a mixture of Trues and Falses however it only outputs Trues. I have checked and seen that $(($(($i - $j)) > 1)) is correctly producing 0s and 1s as it is supposed to but apparently the if statement is not registering these and always assumes "True".

Am I missing something in my code?

Thank you very much

James

2
  • $(($(($i - $j)) > 1)) wut? Try this (( i - j > 1)) Commented Jun 23, 2014 at 14:59
  • 2
    if (( i - j > 1 )); then Commented Jun 23, 2014 at 15:00

2 Answers 2

2

Your script is checking if [ 0 ] and if [ 1 ] which isn't what you think. It will always return true because it is checking that the length of the string 0 and 1 is not zero.

Change it to:

for j in {0..5}
do
    for (( i=j; i<=5; i++ ))
    do
        if (( i - j > 1 ))
        then
            echo True
        else
            echo False
        fi
    done
done

Note that the use of the $ prefix for variables within ((...)) is optional.

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

Comments

0

You're using if incorrectly, you're testing for string length when you want an arithmetic comparison:

for j in {0..5}; do
    for i in $(seq $j 5); do
        if (( i - j > 1 )); then
            echo "True"
        else
            echo "False"
        fi
    done
done

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.