Custom Error Handling के लिए trap ERR
In this page:
trap 'commands' ERR
set -e
एक Basic ERR Trap
trap handler ERR code register करता है जो script में एक command fail होने पर अपने आप run होता है, उन्हीं situations में जहां set -e आमतौर पर इसे रोक देता।
उदाहरण: A Basic ERR Trap
#!/bin/bash
(
trap 'echo "an error was trapped"' ERR
set -e
false
echo "unreached"
) || echo "subshell exited after the ERR trap ran"
Login to try C/C++/Java/PHP code in the editor
Failing Line Number Report करना
एक ERR trap के अंदर, $LINENO उस line number को reflect करता है जहां failure हुई, जो actual bug pinpoint करने के लिए error messages को कहीं ज़्यादा उपयोगी बनाता है।
उदाहरण: Reporting the Failing Line Number
#!/bin/bash
(
trap 'echo "error occurred near line $LINENO"' ERR
set -e
true
false
) || echo "handled"
Login to try C/C++/Java/PHP code in the editor
ERR Traps को Functions के अंदर काम करने देना
By default, एक ERR trap functions या command substitutions के अंदर propagate नहीं होता। set -o errtrace (equivalently set -E) trap को extend करता है ताकि यह चाहे failure कहीं भी हो, fire हो।
उदाहरण: Making ERR Traps Work Inside Functions
#!/bin/bash
(
set -E -e
trap 'echo "caught failure inside a function"' ERR
fail_inside() {
false
}
fail_inside
echo "unreached"
) || echo "subshell stopped after the function's failure was trapped"
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि
trap ERRउन commands के लिए भी fire होता है जोset -eसे exempt हैं (जैसे एकifcondition); यह वही exemptions share करता है। - यह भूल जाना कि
trap ERRतभी reliably fire होता है जब उस command के लिएset -esemantics effect में हों; अन्यथा functions जैसे contexts में behavior inconsistent हो सकता है जब तकset -E(errtrace) भी उपयोग न किया जाए। - एक ERR handler लिखना जो खुद fail हो सकता है, confusing recursive या missed error handling का कारण बनते हुए।
trap handler ERRhandlerrun करता है जब भी एक command fail हो, उन्हीं contexts में जहांset -etrigger होता।set -o errtrace(set -E) ERR trap को functions और subshells के अंदर भी fire करता है, सिर्फ top-level commands में नहीं।- एक ERR trap आमतौर पर script exit होने से पहले diagnostic information (जैसे
$LINENOके through failing line number) log करने के लिए उपयोग किया जाता है। trap ERRको एक EXIT trap के साथ combine करना error-specific logging को general cleanup से अलग करने देता है जो हमेशा run होना चाहिए।
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