我想在用户提供多个输入的情况下验证用户输入
例子:
read order_number city cost
如果用户输入类似于texas 200
输入的内容,我应该能够识别缺少订单号,当我尝试以下操作时,它总是说缺少成本:
read order_number city cost
echo ""
echo "Job details you have entered are:" $order_number $city $cost
echo ""
if [[ $order_number == '' ]] then
echo "Order number can't be null"
exit;
elif [[ $city == '' ]] then
echo "city can't be null"
exit;
elif [[ $cost == '' ]] then
echo "cost can't be null"
exit;
fi
答案1
根据每个变量必须满足的条件,您可以使用此脚本:
#!/usr/bin/bash
read order_number city cost
#Check if order_number is set
# Validate order_number starts with any number(s)
# followed by 0 or more letters and can finish with any letter or number
grep -E --silent "^[0-9]+[A-Za-z]*" <<< "$order_number" || {
echo "'order_number' cannot be null."
exit 1
}
#Check if city is set (starts with some letter followed by underscores or more letters )
grep -E --silent "^[A-Za-z][A-Za-z_]+$" <<< "$city" || {
echo "'city' cannot be null."
exit 1
}
#Check if cost is set (validate is a number)
grep -E --silent "^[0-9]+$" <<< "$cost" || {
echo "'cost' cannot be null (and must be an Integer)"
exit 1
}
例如,读取此字符串"102w1 Texas_ some"
将导致:
'cost' cannot be null (and must be an Integer)
尽管cost
已读取,但该some
值不是数字,因此将被视为null
。
如果您确实认为该字符串some
不为空(对于成本变量),那么实现您想要的将会更加困难。
提示
你可以测试你的script
bash非交互式通过使用这个方式:
./script < <(echo -n "102w1 Texas_ 30")
当我测试此类脚本时,使用上面的代码可以节省时间:)。