Manejo de errores con Bash

En casi todo script de Bash que hago termino chequeando si los comandos que ejecuto tuvieron éxito o no y terminando el script en caso de haber fallado. Esto hace que el script se llene de líneas como:

[ $? -ne 0 ] && exit 1

abajo de cada comando que ejecuto. O sino llamando a una función que hace eso mismo. Hace poco encontré que usando set -e al principio del script me evito tener que chequear manualmente si los comandos que ejecuté dieron error. Hace que el script termine si cualquier comando que se ejecuta falla (bah, devuelve un código > 0). Según el man de Bash:

Exit immediately if a simple command (see SHELL  GRAMMAR above) exits with a non-zero status.  The shell does not exit if the command that fails is part  of  the  command list  immediately  following  a  while or until keyword, part of the test in an if statement, part of a && or  || list, or if the command’s return value is being inverted via !.  A trap on ERR, if set, is  executed  before  the shell exits.

Categorías: Investigacion

Leave a comment