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

set -e और set -u

set -e एक fire alarm जैसा है जो कुछ गलत होते ही game रोक देता है, और set -u चिल्लाता है अगर आप एक ऐसा label उपयोग करें जो आपने कभी भरा ही नहीं।

In this page:

  1. set -e and set -u
Syntax
bash
set -e    # exit on error
set -u    # error on unset variables

set -e and set -u

set -e एक script को तुरंत exit करता है अगर कोई भी command fail हो जाए (non-zero return करे), continue करने और potentially cascading damage करने के बजाय।

set -u एक undefined variable को reference करने को silently एक empty string में expand होने के बजाय एक error बनाता है, typos को early catch करते हुए। Script के top के पास दोनों को combine करना एक widely recommended defensive habit है।

Note:
  • set -euo pipefail एक common combo है:
  • -e errors के लिए
  • -u undefined variables के लिए
  • pipefail ताकि pipeline के बीच में एक failing command भी catch हो।

उदाहरण: set -e and set -u

bash
#!/bin/bash
set -eu

echo "Starting script with strict mode enabled"
name="Bash"
echo "Hello, $name!"
# echo "$undefined_var" would cause an immediate error under set -u
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. set -e उपयोग करना और यह उम्मीद करना कि यह हर failure catch करेगा, क्योंकि यह conditions या pipelines में apply नहीं होता।
  2. set -u उपयोग करना और एक optional variable reference करना, जो script रोक देता है; ${var:-} उपयोग करें।
  3. set -o pipefail भूल जाना, इसलिए pipeline में एक failing command ignore हो जाती है।

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.