-2

In my problem, it appears like j value and i value reach 6; where i should only run up to 5. Can someone please explain ?

i=0;
j=0;
echo "values of $i and $j" > debug.txt;
while [ $j -le 5 ]
do
    j=expr $j + 1
    i=expr $i + 1
    echo "values of $i and $j" >> debug.txt
done;
cat debug.txt;

OUTPUT :

value of i is  0 and j is  0
value of i is  1 and j is  1
value of i is  2 and j is  2
value of i is  3 and j is  3
value of i is  4 and j is  4
value of i is  5 and j is  5
value of i is  6 and j is  6
1
  • Downvoted, this is a simple logic error, and should have been noticed by the coder. Simple debugging, dude. May 23, 2016 at 15:26

1 Answer 1

1

The reason why your script isn't working is because you are using -le. This causes your script to think that when it reaches 5, it will still execute because it is equal to 5. Change the -le to -lt.

6
  • Dude, anyway it should not go beyond 5 right ...
    – Sai Koti
    May 23, 2016 at 15:28
  • @SaiKoti Listen to the logic here, 5 is less than or equal to 5, execute again. The number increments to 6, and the script stops because 6 is not less than or equal to 5. May 23, 2016 at 15:30
  • let me try in another way buddy
    – Sai Koti
    May 23, 2016 at 15:32
  • @SaiKoti What the hell are you talking about!? If you ABSOLUTELY need to use -le, use [ $j -le 4 ]. May 23, 2016 at 15:34
  • So, Previously what i thought that ...during the execution of while loop, if the value exceeds 5 in the body then it will come out of that loop immediately. Now i got that, only when entering that loop, it will check for the value. Thanks for the help ;)
    – Sai Koti
    May 23, 2016 at 15:35

Not the answer you're looking for? Browse other questions tagged .