Error को Handle करना
Error handling यह check करने जैसा है कि एक cake serve करने से पहले असल में oven से ठीक निकली या नहीं। आपका script यह देखता है कि हर important step काम किया या नहीं और एक helpful message के साथ react करता है।
In this page:
Syntax
if ! command; then
echo "error message" >&2
exit 1
fi
command || handle_error
Error Handling
set -e से आगे, scripts को critical commands का exit status explicitly check करना चाहिए ($? के through या सीधे एक if में) और उसके according respond करना चाहिए, जैसे एक message print करना और exit करना।
Risky sections को wrap करना और results check करना failure modes को accidental के बजाय intentional बनाता है। अच्छी error handling एक script को silently गलत results produce करने के बजाय loudly और clearly fail करवाती है।
Note:
Error messages को
>&2 से stderr पर print करें ताकि वे script के normal output stream में mix न हों।उदाहरण: Error Handling
#!/bin/bash
run_task() {
false # simulate a failing command
}
(
if run_task; then
echo "Task succeeded"
else
echo "Error: task failed" >&2
exit 1
fi
)
echo "Subshell exited with status $?, script continues"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- Exit codes को ignore करना, इसलिए script एक failure के बाद भी चलता रहता है।
- Errors को standard output पर print करना बजाय
>&2के। exitको गलत number के साथ उपयोग करना, क्योंकि 0 का मतलब success है।
🔒
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