Syntax for a single-line while loop in Bash
824,735
Solution 1
while true; do foo; sleep 2; done
By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.
$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do echo "hello"; sleep 2; done
Solution 2
It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.
while sleep 2; do echo thinking; done
Solution 3
Colon is always "true":
while :; do foo; sleep 2; done
Solution 4
You can use semicolons to separate statements:
$ while [ 1 ]; do foo; sleep 2; done
Solution 5
You can also make use of until
command:
until ((0)); do foo; sleep 2; done
Note that in contrast to while
, until
would execute the commands inside the loop as long as the test condition has an exit status which is not zero.
Using a while
loop:
while read i; do foo; sleep 2; done < /dev/urandom
Using a for
loop:
for ((;;)); do foo; sleep 2; done
Another way using until
:
until [ ]; do foo; sleep 2; done
Author by
Brian Deacon
Updated on July 16, 2022Comments
-
Brian Deacon almost 2 years
I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:
while [ 1 ] do foo sleep 2 done