[英]Check whether input is an integer and equal to a specific number in bash
嘗試檢查用戶輸入的值是否是 integer 以及等於 35 或 75。如果輸入的值是 integer 並且等於 35 或 75,那么我想通知用戶這一點。 如果輸入的值不是 35 或 75(例如字符串、null 或不同的整數),那么我的目標是讓用戶知道它無效並讓他們重試。
read -p 'Please enter an integer that is either equal to 35 or equal to 75: ' value
if [ $value =~ ^[0-9]+$ ] && ([ $value -eq 35 ] || [ $value -eq 75 ]
echo "The input is acceptable"
exit 1
else
echo "The value is invalid. Try again."
fi
exit 0
我一直收到的錯誤是第 10 行:意外標記“else”附近的語法錯誤
你錯過了then
。 我會這樣整理:
#!/bin/bash
read -r -p 'Please enter an integer that is either equal to 35 or equal to 75: ' value
if [[ "$value" =~ ^[0-9]+$ ]] && [ "$value" -eq 35 ] || [ "$value" -eq 75 ]
then
echo "The input is acceptable"
exit 0
else
echo "The value is invalid. Try again."
fi
exit 0
更新:為了不斷提示用戶輸入,請執行以下操作:
#!/bin/bash
while
read -r -p 'Please enter an integer that is either equal to 35 or equal to 75: ' value
do
if [[ "$value" =~ ^[0-9]+$ ]] && [ "$value" -eq 35 ] || [ "$value" -eq 75 ]
then
echo "The input is acceptable"
exit 0
else
echo "The value is invalid. Try again."
fi
done
exit 0
當答案正確時不確定exit 1
,我猜你想做這樣的事情:
#!/bin/bash
read -p 'Please enter an integer that is either equal to 35 or equal to 75: ' value
if [[ $value =~ ^[0-9]+$ && ($value -eq 35 || $value -eq 75) ]]; then
echo "The input is acceptable"
else
echo "The value is invalid. Try again."
exit 1
fi
exit 0
我個人會將其簡化為:
#!/bin/bash
read -p 'Please enter an integer that is either equal to 35 or equal to 75: ' value
if [[ "${value}" == "35" || "${value}" == "75" ]]; then
echo "The input is acceptable"
else
echo "The value is invalid. Try again."
exit 1
fi
exit 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.