Bash脚本年份输入校验问题求助:需实现2018-2099范围验证
Fixing Bash Year Validation Script (2018-2099 Range)
Hey there! Let's get that year validation script working properly. Your current code has two main issues: the regex doesn't correctly enforce the 2018-2099 range, and it exits immediately instead of prompting the user to try again. Here's a revised version with explanations:
Working Script
#!/bin/bash # Loop until valid input is received while true; do read -r -p "Type year [value from 2018-2099]: " year # First, check if input is a 4-digit number in the correct range if [[ "$year" =~ ^20(1[89]|[2-9][0-9])$ ]]; then # Optional numeric check as an extra safeguard if (( year >= 2018 && year <= 2099 )); then mkdir -p "/home/$year/" echo "Successfully created directory /home/$year/" exit 0 fi fi # If we reach here, input was invalid echo "Error: '$year' is not a valid year. Please enter a value between 2018 and 2099." >&2 done
Key Changes Explained
- Loop for re-entry: Used
while trueto keep asking for input until a valid year is provided, instead of exiting on the first mistake. - Corrected regex:
^20(1[89]|[2-9][0-9])$ensures:- The input starts with
20(locking us into the 2000s) - Followed by either
18/19(covers 2018-2019) or20-99(covers 2020-2099)
- The input starts with
- Numeric range check: Added an extra numeric validation step to catch any edge cases the regex might miss (though the regex is solid, this adds robustness).
- Clear error messaging: Updated the error prompt to be more specific, so the user knows exactly what's wrong.
- Consistent range: Aligned the prompt text with your stated requirement of 2018-2099 (your original prompt mentioned 2019, which I fixed to match your goal).
Why Your Original Script Failed
Your regex ^(20[1-9]|[1-9])+$ was matching values like 201, 205, or even single digits (e.g., 5)—it didn't enforce a 4-digit number, let alone the 2018-2099 range. Plus, there was no loop to allow re-entry, so the script just exited immediately on the first invalid input.
内容的提问来源于stack exchange,提问作者Marcin A
相关产品推荐
相关产品推荐

