1

Having trouble getting this to exit the loop and perhaps I don't understand the while loop well enough to get it to stop. This is what I'm typing in my command line. I expect it to stop at 10.

 c=1; while : [[$c -le 10]]; do df -Th; echo "$c";  date; c=`expr $((c+=1))`; sleep 6; done

I've already read article but it didn't seem to help: bash while loop won't stop itself

Final code:

c=1; while [[ $c -le 10 ]]; do df -Th; echo "$c";  date; c=$((c+=1)); sleep 6; done

The final code required removing the : and adding between the [[$c and 10]]

Community
  • 1
  • 1
tenet75
  • 13
  • 6
  • http://stackoverflow.com/questions/3224878/what-is-the-purpose-of-the-colon-gnu-bash-builtin – ewcz Sep 23 '16 at 17:58
  • I sort of knew this, but it seemed every example included the colon. It was an interesting read though. – tenet75 Sep 23 '16 at 18:23
  • 1
    The call to `expr` is unnecessary; the arithmetic expansion does all the work. If `c` is currently 2, then the expression reduces to `c=$(expr 3)`, then `c=3`. but `c` was already set to 3 by the `+=` operator. All you really need is `((c+=1))`. – chepner Sep 23 '16 at 18:40
  • I had that originally, but read the post I shared in original post. FWIW, there were two reasons for my code not working, the colon and the lack of spaces. I do not believe the post you linked to is the full answer. – tenet75 Sep 23 '16 at 18:41

1 Answers1

3

In bash, spaces are important. Replace:

: [[$c -le 10]]

With

[[ $c -le 10 ]]

What went wrong

When bash encounters

: [[$c -le 10]]

it executes the command : with three arguments, [[$c, -le, and 10]]. This is not what you want. First, : is the no-op command: regardless of its arguments, it does nothing. Second, if you want to run the [[ test command, it needs, as shown above, spaces around it.

Alternatives

There are several ways to loop something 10 times in bash. For one:

$ for c in {1..10}; do echo "$c"; done
1
2
3
4
5
6
7
8
9
10

For another:

$ for ((c=1;c<=10;c++)); do echo "$c"; done
1
2
3
4
5
6
7
8
9
10
John1024
  • 97,609
  • 11
  • 105
  • 133