我试图在if语句中执行简单的比较
基本上它是从用户那里获取输入然后检查以验证它是否是正确的条目。
此特定脚本正在检查序列号。
read -p "enter in you serial number: serial_number
if [[ $serial_number == FOO[A-Z0-9]{3}-[A-Z0-9]{4} ]]
then echo -e "validation passed"
else echo -e "validation failed"
fi
但是,如果我输入FOO123-ABCD,我的验证失败。
我能够让它工作的唯一方法是更加丑陋
if $serial_number == [A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]-[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9] ]]
我的花括号是否有问题,或者我是否需要使用一些开关来比较扩展表达式?
到目前为止,我已经尝试过:
[[ "$serial_number" == FOO[A-Z0-9]{3}-[A-Z0-9]{4} ]]
[[ "$serial_number" == "FOO[A-Z0-9]{3}-[A-Z0-9]{4}" ]]
[[ "${serial_number}" == FOO[A-Z0-9]{3}-[A-Z0-9]{4} ]]
[[ "${serial_number}" == "FOO[A-Z0-9]{3}-[A-Z0-9]{4}" ]]
[[ "$serial_number" =~ FOO[A-Z0-9]{3}-[A-Z0-9]{4} ]]
[[ "$serial_number" =~ "FOO[A-Z0-9]{3}-[A-Z0-9]{4}" ]]
[[ "${serial_number}" =~ FOO[A-Z0-9]{3}-[A-Z0-9]{4} ]]
[[ "${serial_number}" =~ "FOO[A-Z0-9]{3}-[A-Z0-9]{4}" ]]
答案 0 :(得分:3)
这对我来说很好:
read -p "enter in you serial number:" serial_number
echo ">>$serial_number<<"
if [[ "$serial_number" =~ ^FOO[A-Z0-9]{3}-[A-Z0-9]{4}$ ]]; then
echo -e "validation passed"
else
echo -e "validation failed"
fi
请注意,您需要^
和$
。否则它会检查字符串中的任何位置(如egrep
)。