如何用getopts实现work.sh脚本中-1与-2标志的互斥?
Yes, you absolutely can enforce mutually exclusive flags (-1 and -2) using getopts! Here's a practical implementation that aligns with your script's requirements:
Script Usage
./work.sh [options] parm_1 parm_2 parm_3 parm_4
Available Options:
-y year: Specify a year value (requires an argument)-n number: Specify a number value (requires an argument)-1: Flag with no arguments (mutually exclusive with-2)-2: Flag with no arguments (mutually exclusive with-1)
Working Script Implementation
#!/bin/bash # Track usage of mutually exclusive flags flag1_active=false flag2_active=false # Process command-line options with getopts while getopts "y:n:12" opt; do case $opt in y) year_input="$OPTARG" ;; n) number_input="$OPTARG" ;; 1) # Check if -2 was already used if $flag2_active; then echo "Error: Flags -1 and -2 cannot be used together." >&2 exit 1 fi flag1_active=true ;; 2) # Check if -1 was already used if $flag1_active; then echo "Error: Flags -1 and -2 cannot be used together." >&2 exit 1 fi flag2_active=true ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done # Shift processed options to access positional parameters shift $((OPTIND - 1)) # Verify required positional parameters are present if [ $# -ne 4 ]; then echo "Error: Expected 4 positional parameters (parm_1 parm_2 parm_3 parm_4)" >&2 exit 1 fi # Assign positional parameters to variables parm1="$1" parm2="$2" parm3="$3" parm4="$4" # ------------------------------ # Add your script logic below # ------------------------------ echo "Year specified: $year_input" echo "Number specified: $number_input" echo "Flag -1 active: $flag1_active" echo "Flag -2 active: $flag2_active" echo "Positional params: $parm1 $parm2 $parm3 $parm4"
Key Details Explained
- Mutual Exclusivity Check: We use boolean variables to track if either flag has been activated. When processing
-1or-2, we immediately check if the other flag was already used—if so, we throw an error and exit. - getopts String:
"y:n:12"tellsgetoptsthat-yand-nrequire arguments (marked by the colon), while-1and-2are standalone flags. - Error Handling: All error messages are sent to stderr (
>&2) for proper command-line behavior, and we exit with a non-zero code to signal failure.
Test Scenarios
- Valid:
./work.sh -y 2024 -n 10 -1 alpha beta gamma delta→ Runs successfully - Valid:
./work.sh -2 one two three four→ Runs successfully - Invalid:
./work.sh -1 -2 a b c d→ Throws error: "Error: Flags -1 and -2 cannot be used together."
内容的提问来源于stack exchange,提问作者DamienzOnly
相关产品推荐
相关产品推荐

