Custom Error/die Function लिखना
In this page:
die() {
echo "ERROR: $1" >&2
exit "${2:-1}"
}
die "error message" exit_code
एक Basic die Function
एक die function इसकी message stderr पर print करता है और फिर exit करता है, script में फैले हुए repeated echo ... >&2; exit 1 blocks को एक reusable call से replace करते हुए।
उदाहरण: A Basic die Function
#!/bin/bash
die() {
echo "ERROR: $1" >&2
exit 1
}
check_positive() {
if (( $1 <= 0 )); then
die "value must be positive, got $1"
fi
echo "$1 is positive"
}
check_positive 5
Login to try C/C++/Java/PHP code in the editor
एक Custom Exit Code Support करना
Exit code के लिए एक optional second argument accept करना अलग failure conditions को script के final exit status inspect कर रहे एक caller द्वारा distinguish किए जाने देता है।
उदाहरण: Supporting a Custom Exit Code
#!/bin/bash
die() {
local message=$1
local code=${2:-1}
echo "ERROR: $message" >&2
exit "$code"
}
(
die "config file missing" 2
)
echo "the subshell that called die exited with status $?"
Login to try C/C++/Java/PHP code in the editor
Validation Call Sites पर die उपयोग करना
एक बार defined हो जाने पर, die validation के point पर naturally पढ़ता है: condition || die "message" एक compact, readable guard clause है।
उदाहरण: Using die at Validation Call Sites
#!/bin/bash
die() {
echo "ERROR: $1" >&2
exit 1
}
required_tool="bash"
command -v "$required_tool" > /dev/null || die "$required_tool is required but not found"
echo "$required_tool is available, continuing"
Login to try C/C++/Java/PHP code in the editor
- Error message stdout पर लिखना जब इसे stderr पर जाना चाहिए, diagnostics को normal program output के साथ mix करते हुए।
- die function के अंदर actually
exitcall करना भूल जाना, जो सिर्फ message print करता है लेकिन script को एक broken state में चलते रहने देता है। - हर failure के लिए एक single generic exit code उपयोग करना, callers के लिए सिर्फ script के exit status से अलग kinds of errors distinguish करना impossible बनाते हुए।
- एक
diefunction error reporting को centralize करता है: stderr पर print करो, फिर एक non-zero status के साथ exit करो। - एक optional exit code argument accept करना अलग call sites को अलग failure types signal करने देता है।
- stderr (
>&2) पर print करना error messages को script के normal stdout output से अलग रखता है। - एक
diefunction call sites को cleanly पढ़वाता है, जैसे[[ -f $file ]] || die "missing file: $file"।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments