set -e और set -u
set -e एक fire alarm जैसा है जो कुछ गलत होते ही game रोक देता है, और set -u चिल्लाता है अगर आप एक ऐसा label उपयोग करें जो आपने कभी भरा ही नहीं।
In this page:
Syntax
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 है:-eerrors के लिए-uundefined variables के लिएpipefailताकि pipeline के बीच में एक failing command भी catch हो।
उदाहरण: set -e and set -u
#!/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
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. #}
आम गलतियां
set -eउपयोग करना और यह उम्मीद करना कि यह हर failure catch करेगा, क्योंकि यह conditions या pipelines में apply नहीं होता।set -uउपयोग करना और एक optional variable reference करना, जो script रोक देता है;${var:-}उपयोग करें।set -o pipefailभूल जाना, इसलिए pipeline में एक failing command ignore हो जाती है।
🔒
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