
ユーザーが複数の入力を提供する場合は、ユーザー入力を検証したいと思います。
例:
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
バッシュをテストできます非対話型これを使用すると:
./script < <(echo -n "102w1 Texas_ 30")
上記のコードを使用すると、そのようなスクリプトをテストするときに時間が節約されます。 :)