我需要从< 2018-2099>获取价值,如果用户输入错误的值,那么脚本会告诉他该值不正确并要求他再次输入。
我已经有类似的东西,但它不起作用.. 有什么建议吗?
#!/bin/bash
read -r -p "Type year [value from 2019-2099]" year
if [[ "$year" =~ ^(20[1-9]|[1-9])+$ ]]; then
mkdir -p "/home/$year/"
else
echo "$year - value is not correct. Try again." >&2 && exit 1
fi
答案 0 :(得分:1)
你可以试试这个:
until
read -r -p "Type year [2019-2099]: " year
[[ $year =~ ^2[0-9]+$ ]] && (( year >= 2018 && year <= 2099 ))
do
echo "Incorrect value" >&2
done
echo "OK: $year"
答案 1 :(得分:1)
您可以使用函数和until
循环来实现此目的,请考虑以下代码:
readYear() {
read -r -p "Type year [value from 2018-2099]" year
[[ "${year}" =~ ^[0-9]{4}$ ]] && [[ "${year}" -ge 2018 ]] && [[ "${year}" -le 2099 ]]
}
until readYear; do
echo "${year} - value is not correct. Try again." >&2
done
如果输入的值有效,则函数返回0,然后循环终止。