Search code examples
basherror-handlingcustom-error-handling

Linux Bash Shell Custom Error Message


I'm trying to spew a custom error message using the following 1 liner bash shell command. I'm not getting the "errorMessage" var set. However if I run the command individually, I'm able to capture the error message into $errorMessage variable. What am I missing?

Command:

[ "errorMessage=$(mkdir -p /path/to/restricted/folder 2>&1)" ] && echo "Something Went Wrong; Error is: ${errorMessage}"

Trials/Output:

$ [ "errorMessage=$(mkdir -p /path/to/restricted/folder 2>&1)" ] && echo "Something Went Wrong; Error is: ${errorMessage}"
Something Went Wrong; Error is:
$ echo $errorMessage

$ errorMessage=$(mkdir -p /path/to/restricted/folder 2>&1)
$ echo $errorMessage
mkdir: cannot create directory `/path': Permission denied

Solution

  • [ is the command named test; when not given an argument specifying an individual test to run, the default is -n (testing whether a string is empty). This code is testing whether the string "errorMessage=" (possibly with a suffix from the stderr of mkdir) is empty or not; since it contains a fixed prefix, it will never be empty, whether any error was emitted or not.

    If you want to actually assign a value to the variable, that would instead look like:

    errorMessage=$(mkdir -p /path/to/restricted/folder 2>&1) \
      || echo "Something Went Wrong; Error is: ${errorMessage}"
    

    This is checking the exit status of mkdir, and running the echo should that be nonzero.