Bash脚本选项处理需求:新增-all与-q选项并限制重复
Alright, let's work through adding these two new options to your Bash script. I'll break this down into clear, actionable steps that fit your existing rules:
Start by initializing variables to track the new states and keep track of selected original options:
#!/bin/bash # Track silent mode state silent=false # Track whether -all was triggered select_all=false # Store manually selected -1/-2/.../-N options selected_options=() # Define your N value here (e.g., N=5 for options -1 to -5) N=5
Use a while loop with case statements to handle each argument—this is flexible enough to support both your existing single-digit options and the new multi-character -all/-q:
while [[ $# -gt 0 ]]; do case "$1" in -q) # Enable silent mode silent=true shift ;; -all) # Mark that all options should be selected select_all=true shift ;; -[1-9]|[1-9]) # Catch your original -1 to -N options (adjust regex if N is 10+) selected_options+=("$1") shift ;; *) # Handle unknown options echo "Error: Unknown option '$1'" >&2 exit 1 ;; esac done
-all Logic If -all was passed, add all -1 to -N options to your selected list. We'll also avoid duplicates if someone accidentally passes -all alongside a specific option:
if $select_all; then for ((i=1; i<=N; i++)); do opt="-$i" # Only add if not already in selected_options if ! [[ " ${selected_options[@]} " =~ " $opt " ]]; then selected_options+=("$opt") fi done fi
Enforce -all Usage Rules
You mentioned -all must appear alone or with "specified options"—I assume this means it can be used with -q but not with your original -1/-2 etc. If that's the case, modify the -all case block to throw an error if any original options are already selected:
-all) if [[ ${#selected_options[@]} -gt 0 ]]; then echo "Error: -all cannot be combined with individual -1/-2/.../-N options" >&2 exit 1 fi select_all=true shift ;;
If -q was passed, redirect all terminal output (including errors) to /dev/null to ensure no output is sent to the user:
if $silent; then exec >/dev/null 2>&1 fi
Now you can use the selected_options array in your original script logic. For example:
# Example: Print selected options (will be suppressed if -q is used) echo "Selected options: ${selected_options[@]}" # Insert your original script logic here, using selected_options as needed
./yourscript.sh -all: Selects all-1to-Noptions./yourscript.sh -q: Runs silently with no selected options./yourscript.sh -all -q: Selects all options and runs silently./yourscript.sh -1 -3: Selects only-1and-3./yourscript.sh -all -2: Throws an error (if you enforced the-allusage rule above)
内容的提问来源于stack exchange,提问作者Dave

