Sintaxis para un bucle while infinito Bash de una sola línea


Estoy teniendo problemas para encontrar la combinación correcta de punto y coma y/o llaves. Me gustaría hacer esto, pero como una línea de la línea de comandos:

while [ 1 ]
do
    foo
    sleep 2
done
Author: codeforester, 2009-08-17

11 answers

while true; do foo; sleep 2; done

Por cierto, si lo escribe como una línea múltiple (como se muestra) en el símbolo del sistema y luego llama al historial con la flecha hacia arriba, lo obtendrá en una sola línea, correctamente puntuada.

$ while true
> do
>    echo "hello"
>    sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do    echo "hello";    sleep 2; done
 935
Author: Stefano Borini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-17 16:32:32

También es posible usar el comando sleep en la condición de while. Haciendo que un revestimiento luzca más limpio en mi humilde opinión.

while sleep 2; do echo thinking; done
 137
Author: Anssi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 10:34:41

Los dos puntos siempre son "verdaderos":

while :; do foo; sleep 2; done
 59
Author: ajaaskel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 13:35:49

Puede usar punto y coma para separar las sentencias:

$ while [ 1 ]; do foo; sleep 2; done
 24
Author: mipadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-17 16:32:41

También puede hacer uso de until comando:

until ((0)); do foo; sleep 2; done

Tenga en cuenta que en contraste con while, until ejecutaría los comandos dentro del bucle siempre y cuando la condición de prueba tenga un estado de salida que no sea cero.


Usando un bucle while:

while read i; do foo; sleep 2; done < /dev/urandom

Usando un bucle for:

for ((;;)); do foo; sleep 2; done

Otra manera usando until:

until [ ]; do foo; sleep 2; done
 22
Author: devnull,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-16 07:44:32

Me gusta usar el punto y coma solo para la instrucción WHILE, y el operador && para hacer que el bucle haga más de una cosa...

Así que siempre lo hago así

while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done
 6
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-30 00:29:09

Un bucle infinito muy simple.. :)

while true ; do continue ; done

Fr su pregunta sería:

while true; do foo ; sleep 2 ; done
 6
Author: Mack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-26 20:10:46

Para ver procesos simples, use watch en su lugar

 4
Author: Christian Schwarz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-14 11:36:20

Si puedo dar dos ejemplos prácticos (con un poco de "emoción").

Esto escribe el nombre de todos los archivos terminados con ".jpg " en la carpeta "img":

for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done

Esto los elimina:

for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done

Solo intento contribuir.

 1
Author: Roger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-02 16:32:48

Si desea que el bucle while se detenga después de alguna condición, y su comando foo devuelve distinto de cero cuando se cumple esta condición, entonces puede hacer que el bucle se rompa de la siguiente manera:

while foo; do echo 'sleeping...'; sleep 5; done;

Por ejemplo, si el comando foo está borrando cosas por lotes, y devuelve 1 cuando no queda nada por eliminar.

Esto funciona bien si tiene un script personalizado que necesita ejecutar un comando muchas veces hasta que se cumpla alguna condición. Escribe el script para salir con 1 cuando la condición es met y exit con 0 cuando se debe ejecutar de nuevo.

Por ejemplo, supongamos que tiene un script python batch_update.py que actualiza 100 filas en una base de datos y devuelve 0 si hay más que actualizar y 1 si no hay más. El siguiente comando le permitirá actualizar las filas 100 a la vez con reposo durante 5 segundos entre actualizaciones:

while batch_update.py; do echo 'sleeping...'; sleep 5; done;
 1
Author: Yep_It's_Me,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-18 02:30:48

Puedes probar esto también ADVERTENCIA: esto no debe hacer, pero ya que la pregunta es pedir bucle infinito sin fin...así es como podrías hacerlo.

while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done
 1
Author: CPU 100,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 14:16:42