Exception handling in shell scripting?

Viewed 107098

I'm looking for exception handling mechanism in shell script. Is there any try,catch equivalent mechanism in shell script ?

5 Answers

Use following to handle error properly where error_exit is function that accepts one argument. In case if argument is not passed then it will throw unknown error with LineNo where actually error is happening. Please experiment before actually uses for production -

#!/bin/bash

PROGNAME=$(basename $0)

error_exit()

{

    echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
    exit 1
}

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."
Related