Why is an empty line invalid in a shell script?

I wanted to make my shell script infinitely infinite, and thought the code below would do it.

#!/bin/bash
while true
do
done

However, the above script reports a syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected done token

./Infinite_Loop.sh: line 4: `done '

Unlike programming languages, why does a shell script expect at least one statement in loops?

+4
source share
4 answers

I wanted to make my shell script infinitely infinite

If your system supports it, use:

sleep infinity

If your system does not support it, use sleepat large intervals:

while :; do sleep 86400; done

Note:

  • while : while true / fork, , true ( ).

, .

:

  • 100% - - .
  • .
  • , , ,

shell script?

... while bash :

while list-1; do list-2; done

list-2, while.

, noop (:) - , list-2.

: :

: [arguments]
    No effect; the command does nothing beyond expanding arguments and performing any
    specified redirections.  A zero exit code is returned.
+7

true , man-: true - ,

while true; do true; done
+1

- NOP (no op), .

bash NOP :.

while true; do
  :
done
+1

Bash s. , :

while:

while test-commands; do consequent-commands; done

, Bash, while loop:

shell_command:  ...
    |   WHILE compound_list DO compound_list DONE

If you check the compound_lists definition , you will see that it must contain at least one shell command; it cannot be empty.

There is no reason to write an empty (infinite) loop if you do not want to heat your processor and drain the battery. This is probably why Bash forbid empty loops.

As others have stated, you can use either true, or :(the latter is an alias for the former ):

while true; do true; done
while :; do :; done
+1
source

Source: https://habr.com/ru/post/1680964/


All Articles