Bash/sh - diferencia entre && y;


Normalmente uso ; para combinar más de un comando en una línea, pero algunas personas prefieren &&. ¿Hay alguna diferencia? Por ejemplo, cd ~; cd - y cd ~ && cd - parecen hacer lo mismo. ¿Qué versión es más portátil, por ejemplo, será compatible con un bash-subconjunto como shell de Android o así?

Author: mklement0, 2011-05-27

7 answers

Si el comando anterior falló con ; se ejecutará el segundo.

Pero con && el segundo no se ejecutará.

Este es un operando "perezoso" lógico "Y" entre operaciones.

 140
Author: ignar,
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-04-16 08:11:03

Estoy usando && porque hace mucho tiempo en el ordenador cercano:

root# pwd
/
root# cd /tnp/test; rm -rf *
cd: /tnp/test: No such file or directory
...
... and after a while ...
...   
^C

, Pero no ayudó... ;)

cd /tnp/test && rm -rf * es seguro... ;)

 40
Author: jm666,
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
2017-05-30 15:12:38

En cmd1 && cmd2, cmd2 solo se ejecuta si cmd1 tiene éxito (devuelve 0).

En cmd1 ; cmd2, cmd2 se ejecuta en cualquier caso.

Ambas construcciones son parte de un shell compatible con POSIX.

 16
Author: Pascal Cuoq,
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-05-27 13:12:44

Los comandos separados por ; se ejecutan secuencialmente independientemente de su estado de finalización.

Con &&, el segundo comando se ejecuta solo si el primero se completa correctamente (devuelve el estado de salida de 0).

Esto está cubierto en la página de manual de bash bajo Lists. Esperaría que cualquier shell tipo Unix soportara ambos operadores, pero no conozco específicamente el shell de Android.

 5
Author: Dave Costa,
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-05-27 13:13:18

&& significa ejecutar el siguiente comando si el anterior salió con el estado 0. Para lo contrario, use || es decir, para ser ejecutado si el comando anterior sale con un estado no igual a 0 ; se ejecuta siempre.

Muy útil cuando necesita realizar una acción en particular dependiendo de si el comando anterior terminó bien o no.

 5
Author: Fredrik Pihl,
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-05-27 13:28:10

&& permite la ejecución condicional mientras que ; siempre tiene el segundo comando siendo ejecutado.

En e. g.command1 && command2, command2 solo se ejecutará cuando command1 haya terminado con exit 0, indicando que todo salió bien, mientras que en command1 ; command2 el segundo comando siempre se ejecutará sin importar el resultado de command1.

 3
Author: Marcel,
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-05-27 19:08:54

&& es lógico Y en bash. Bash tiene evaluación de cortocircuito de lógica Y. Este modismo es una forma más simple de expresar lo siguiente:


cmd1;rc=$?
if [ $rc -eq 0 ]; then
   cmd2
fi

Mientras que la versión ; es simplemente:


cmd1
cmd2
 1
Author: frankc,
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-05-27 15:48:24