Scripting is one of the key tools for a sysadmin to manage a set of day-to-day activities such as running backups, adding users/groups, installing/updating packages, etc. While writing a script, error handling is one of the crucial things to manage.
This article shows some basic/intermediate techniques of dealing with error handling in Bash scripting. I discuss how to obtain the error codes, get verbose output while executing the script, deal with the debug function, and standard error redirection. Using these techniques, sysadmins can make their daily work easy.
[ Readers also liked: Bash command line exit codes demystified ]
Exit status
In Bash scripting, $? prints the exit status. If it returns zero, it means there is no error. If it is non-zero, then you can conclude the earlier task has some issue.
A basic example is as follows:
$ cat myscript.sh
#!/bin/bash
mkdir learning
echo $?
If you run the above script once, it will print 0 because the directory does not exist, therefore the script will create it. Naturally, you will get a non-zero value if you run the script a second time, as seen below:
$ sh myscript.sh
mkdir: cannot create directory 'learning': File exists
1
Best practices
It is always recommended to enable the debug mode by adding the -e option to your shell script as below:
$ cat test3.sh
!/bin/bash
set -x
echo "hello World"
mkdiir testing
./test3.sh
+ echo 'hello World'
hello World
+ mkdiir testing
./test3.sh: line 4: mkdiir: command not found
You can write a debug function as below, which helps to call it anytime, using the example below:
$ cat debug.sh
#!/bin/bash
_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}
DEBUG echo 'Testing Debudding'
DEBUG set -x
a=2
b=3
c=$(( $a + $b ))
DEBUG set +x
echo "$a + $b = $c"
Which prints:
$ ./debug.sh
Testing Debudding
+ a=2
+ b=3
+ c=5
+ DEBUG set +x
+ '[' on == on ']'
+ set +x
2 + 3 = 5
Standard error redirection
You can redirect all the system errors to a custom file using standard errors, which can be denoted by the number 2. Execute it in normal Bash commands, as demonstrated below:
$ mkdir users 2> errors.txt
$ cat errors.txt
mkdir: cannot create directory ‘users’: File exists
Most of the time, it is difficult to find the exact line number in scripts. To print the line number with the error, use the PS4 option (supported with Bash 4.1 or later). Example below:
$ cat test3.sh
#!/bin/bash
PS4='LINENO:'
set -x
echo "hello World"
mkdiir testing
You can easily see the line number while reading the errors:
$ /test3.sh
5: echo 'hello World'
hello World
6: mkdiir testing
./test3.sh: line 6: mkdiir: command not found
[ Get this free ebook: Managing your Kubernetes clusters for dummies. ]
Wrap up
Managing errors is a key skill for administrators when writing scripts. These tips should help make your life easier when troubleshooting Bash scripts or even general commands.
Sobre el autor
Ashutosh is an open source software advocate, docker community leader, Fedora active contributor, Red Hat / SUSE Certified Instructor with 19 years of experience as a trainer and consultant.
Más como éste
Data-driven automation with Red Hat Ansible Automation Platform
More than meets the eye: Behind the scenes of Red Hat Enterprise Linux 10 (Part 4)
Technically Speaking | Taming AI agents with observability
A composable industrial edge platform | Technically Speaking
Navegar por canal
Automatización
Las últimas novedades en la automatización de la TI para los equipos, la tecnología y los entornos
Inteligencia artificial
Descubra las actualizaciones en las plataformas que permiten a los clientes ejecutar cargas de trabajo de inteligecia artificial en cualquier lugar
Nube híbrida abierta
Vea como construimos un futuro flexible con la nube híbrida
Seguridad
Vea las últimas novedades sobre cómo reducimos los riesgos en entornos y tecnologías
Edge computing
Conozca las actualizaciones en las plataformas que simplifican las operaciones en el edge
Infraestructura
Vea las últimas novedades sobre la plataforma Linux empresarial líder en el mundo
Aplicaciones
Conozca nuestras soluciones para abordar los desafíos más complejos de las aplicaciones
Virtualización
El futuro de la virtualización empresarial para tus cargas de trabajo locales o en la nube