← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 3 of 12

Error को Handle करना

Error handling यह check करने जैसा है कि एक cake serve करने से पहले असल में oven से ठीक निकली या नहीं। आपका script यह देखता है कि हर important step काम किया या नहीं और एक helpful message के साथ react करता है।

In this page:

  1. Error Handling
Syntax
bash
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

bash
#!/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"
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. #}
आम गलतियां
  1. Exit codes को ignore करना, इसलिए script एक failure के बाद भी चलता रहता है।
  2. Errors को standard output पर print करना बजाय >&2 के।
  3. exit को गलत number के साथ उपयोग करना, क्योंकि 0 का मतलब success है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.