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

getopts के साथ Script Arguments

getopts एक receptionist जैसा है जो आपके द्वारा command में जोड़े गए छोटे switches पढ़ता है, जैसे एक flag और इसकी value, और उन्हें आपके script को neatly handover कर देता है।
Syntax
bash
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

bash
#!/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"
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. किसी option letter के बाद colon लगाना भूल जाना जिसे एक value चाहिए।
  2. Options parse करने के बाद shift $((OPTIND-1)) उपयोग करना भूल जाना।
  3. यह उम्मीद करना कि getopts --help जैसे long options handle करेगा।

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.