When I read this answer about $? another question comes to mind.Is there any best practice for how to use $? in bash?Let's have a example:We have a linear script and I we would like to know that all the command was executed ok.Do you think it is ok to call a small function (let's call it did_it_work), to check the error code and break if it's not.#!/bin/bash function did_it_work {    code=$1    if [ $code -ne 0 ]    then        echo Error failure: code $code         exit 1    fi}dir=some/pathmkdir -p $dirdid_it_work $? cd $dirdid_it_work $? run_some_commanddid_it_work $? This approach of course means that I have to manually solve the problem if there is any and rerun the script.Do you think this is a good idea or is there some other best practice to do this?/Thanks
Best practice to use $? in bash?
shell;bash;error handling
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 failedJust 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 failedcd some/path || die cd failedrun_some_command || die some_command failedOr you can align the dies further on the right so that the main code is more obvious.mkdir -p some/path         || die mkdir failedcd some/path               || die cd failedrun_some_command           || die some_command failedAlso, 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/pathmkdir -p $dir            || die Cannot make $dircd $dir                  || die Cannot cd to $dirrun_some_command           || die Cannot run some_commandAnd 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 wantdir=some/pathif [ ! -d $dir ]; then    mkdir -p $dir        || die Cannot make $dirficd $dir                  || die Cannot cd to $dirrun_some_command           || die Cannot run some_command