Skip to main content
4 of 6
added 29 characters in body
Mikel
  • 58.7k
  • 16
  • 136
  • 155

One common way is:

die() {
    echo "$*" 1>&2
    exit 1
}

then you use it like this:

mkdir -p some/path || die "mkdir failed with status $?"

Or if you want it to include the exit status, you could change it to:

die() {
    echo "FATAL ERROR: $* (status $?)" 1>&2
    exit 1
}

and then using it is a bit easier:

mkdir -p some/path || die "mkdir failed"

Just in case you haven't seen command1 || command2 before, it runs command1, and if command1 fails, it runs command2.

So you can read it like "make the directory or die".

Your example would look like:

mkdir -p some/path || die "mkdir failed"
cd some/path || die "cd failed"
run_some_command || die "some_command failed"

Or you can align the dies further on the right so that the main code is more obvious.

mkdir -p some/path         || die "mkdir failed"
cd some/path               || die "cd failed"
run_some_command           || die "some_command failed"

Also, if you are going to use the name some/path multiple times, store it in a variable so you don't have to keep typing it, and can easily change it if you need to.

dir=some/path
mkdir -p "$dir"            || die "Cannot make $dir"
cd "$dir"                  || die "Cannot cd to $dir"
run_some_command           || die "Cannot run some_command"

And if you plan to fix the problem and re-run the script, maybe you want the script to work if the directory already exists, so you don't have to remove it first, in which case, you would want

dir=some/path
if [ ! -d "$dir" ]; then
    mkdir -p "$dir"        || die "Cannot make $dir"
fi
cd "$dir"                  || die "Cannot cd to $dir"
run_some_command           || die "Cannot run some_command"
Mikel
  • 58.7k
  • 16
  • 136
  • 155