如何在Bash脚本中展开含方括号数字范围的参数?
It sounds like you're trying to parse and expand range-based arguments (like node-[2,5-7,10-13]) into individual items within your script. Here's a step-by-step solution using bash, focusing on safety and clarity:
Step 1: Extract the prefix and range components
First, split your input argument into the base prefix (e.g., node-) and the range string inside the brackets:
#!/bin/bash # Capture the input argument (e.g., "node-[2,5-7,10-13]") input="$1" # Extract everything before the opening bracket as the prefix prefix=$(echo "$input" | sed -E 's/\[.*\]$//') # Extract the content inside the brackets as the range string range_str=$(echo "$input" | sed -E 's/.*\[([^\]]+)\]$/\1/')
Step 2: Convert ranges to bash brace expansion format
Bash uses .. for continuous ranges in brace expansion, so we'll replace hyphens in our range string with this syntax:
# Replace "-" with ".." to match bash's brace expansion rules brace_range=$(echo "$range_str" | sed 's/-/../g') # Build the full brace pattern (e.g., "node-{2,5..7,10..13}") expanded_pattern="${prefix}{$brace_range}"
Step 3: Expand the pattern into a list of items
Now we can turn this brace pattern into an array of individual items. This method is safe for trusted input:
# Expand the pattern and store it in an array nodes_array=($expanded_pattern)
Step 4: Iterate over the items
You can now loop through the array to process each node:
# Loop through each expanded node item for node in "${nodes_array[@]}"; do echo "Processing: $node" # Add your custom logic here (e.g., connect to the node, run commands) done
Security Note
If your script accepts input from untrusted sources, directly expanding brace patterns can pose a security risk (potential code injection). Add input validation to ensure the range string only contains allowed characters:
# Validate the range string (only digits, commas, and hyphens are permitted) if ! [[ "$range_str" =~ ^[0-9,-]+$ ]]; then echo "Error: Invalid range format. Only digits, commas, and hyphens are allowed." exit 1 fi
Example Usage
Running ./myscript node-[2,5-7,10-13] will output:
Processing: node-2 Processing: node-5 Processing: node-6 Processing: node-7 Processing: node-10 Processing: node-11 Processing: node-12 Processing: node-13
An alternative (but not recommended for untrusted input) is using eval, which executes arbitrary shell code:
# Avoid this if input comes from untrusted sources! eval "nodes_array=($expanded_pattern)"
Content of the question originates from Stack Exchange, asked by Renat

