Error handling
So far, we have looked at how we can check for errors. However, besides checking for errors, there is an aspect to this which is just as important: handling errors. We'll initially combine our previous experience with if
and test
to exit on errors, before we go on to introduce much smarter ways to handle errors!
if-then-exit
As you might recall from the previous chapter, the if-then
construct used by Bash is common to (almost) all programming languages. In its basic form, the idea is that you test for a condition (IF), and if that condition is true, you do something (THEN).
Here's a very basic example: if name
is longer than or equal to 2 characters, then echo "hello ${name}"
. In this case, we assume that a name has to be, at the very least, 2 characters. If it is not, the input is invalid and we do not give it a "hello".
In the following script, if-then-exit.sh
, we will see that our goal is to print the contents of a file using cat
. However, before we do that, we check if the...