Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents

Overview

One of the most common problems with writing any kind of program is lack of proper error handling.

...

So we're going to explore how to add our own error handling mechanisms. This will also force us to better understand shells & sub-shells, exit and result codes, and other communication between execution contexts.

Shells and sub-shells

Every bash program has its own execution environment (sub-shell), which is a child process of its calling parent shell. A new sub-shell is created, runs, and returns when:

...

  • Input to sub-shells
    • program arguments
    • environment variables
    • file or stream data
  • Output from sub-shells
    • exit code
    • standard output
    • file data

Environment variables

In addition to passing arguments to a program, a caller may set environment variables (normal bash shell variables) that can be read in the called environment. However by default, variables in a parent shell are not copied into sub-shells unless they are exported using the export keyword.

Code Block
languagebash
# a normal bash variable is not visible to sub-shells
foo=abc
( echo $foo )

# exported bash variables are visible to sub-shells
export foo
( echo $foo )

export bar="def"
( echo $bar )

Script exit codes and function return values

Unlike most other programming languages, bash functions and scripts can only return a single integer between 0 and 255. By convention a return value of 0 means success, and any other return value is an error code.

...

Tip
titleTip

The $? return code variable must be checked immediately after the called program or sub-shell completes, because any further actions in the caller will change $?. One way to do this is to save off the value $? of in another variable (e.g. res=$?).

exercise 1

On the command line, call exit with various codes in a parentheses sub-shell and check the result in the caller.

...