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.
À propos de l'auteur
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.
Plus de résultats similaires
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
Parcourir par canal
Automatisation
Les dernières nouveautés en matière d'automatisation informatique pour les technologies, les équipes et les environnements
Intelligence artificielle
Actualité sur les plateformes qui permettent aux clients d'exécuter des charges de travail d'IA sur tout type d'environnement
Cloud hybride ouvert
Découvrez comment créer un avenir flexible grâce au cloud hybride
Sécurité
Les dernières actualités sur la façon dont nous réduisons les risques dans tous les environnements et technologies
Edge computing
Actualité sur les plateformes qui simplifient les opérations en périphérie
Infrastructure
Les dernières nouveautés sur la plateforme Linux d'entreprise leader au monde
Applications
À l’intérieur de nos solutions aux défis d’application les plus difficiles
Virtualisation
L'avenir de la virtualisation d'entreprise pour vos charges de travail sur site ou sur le cloud