getopts के साथ Script Arguments
getopts एक receptionist जैसा है जो आपके द्वारा command में जोड़े गए छोटे switches पढ़ता है, जैसे एक flag और इसकी value, और उन्हें आपके script को neatly handover कर देता है।
In this page:
Syntax
while getopts "optstring" option; do
case $option in
a) commands ;;
b) value=$OPTARG ;;
*) usage ;;
esac
done
getopts से Script Arguments
getopts -f file या -v जैसे short command-line flags parse करता है, combined flags और required option arguments जैसे common conventions handle करते हुए।
यह manually $1, $2 check करने के बजाय proper flag parsing के साथ एक script बनाने का standard, POSIX-compatible तरीका है। हर recognized option while getopts loop के अंदर एक case में handle किया जाता है।
Note:
किसी option letter के बाद एक colon, जैसे
"f:", मतलब है कि उस option को एक argument चाहिए।उदाहरण: Script Arguments with getopts
#!/bin/bash
verbose=false
filename=""
while getopts "vf:" opt; do
case $opt in
v) verbose=true ;;
f) filename=$OPTARG ;;
*) echo "Unknown option" ;;
esac
done
echo "Verbose: $verbose"
echo "Filename: $filename"
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. #}
आम गलतियां
- किसी option letter के बाद colon लगाना भूल जाना जिसे एक value चाहिए।
- Options parse करने के बाद
shift $((OPTIND-1))उपयोग करना भूल जाना। - यह उम्मीद करना कि
getopts--helpजैसे long options handle करेगा।
🔒
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