簡體   English   中英

驗證bash腳本中的輸入

[英]Validate input in bash script

我有一個代碼,可以通過給出寬度和高度來找到矩形的區域。

echo -n "Enter width: "
read width

echo -n "Enter height:"
read height

echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"

如何使它只能輸入數字,否則顯示錯誤?

由於您讀取輸入兩次,因此我將使用一個函數來檢查輸入。 這樣,您就不會重復代碼。

這將檢查輸入是否僅包含數字和至少一個數字。 否則,它將繼續要求輸入:

myread () {
  while :                     # infinite loop
  do
     read value
     [[ $value =~ ^[0-9]+$ ]] && echo "$value" && return  #return value if good input
  done
}

echo -n "Enter width: "
width=$(myread)             #call to the funcion and store in $width

echo -n "Enter height: "
height=$(myread)            #call to the funcion and store in $height

echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"

您也許可以使用grep進行檢查,但是如果您想要進行此類檢查,那么bash(通常是shell)實際上是一種不好的語言選擇。

就像是:

echo $width | grep -E -q '^[0-9]+$' || echo "numeral expected!"

你可以做一些這樣的事情

    if [[ -n "$width" ]] ; then

        nodigits="$(echo $width| sed 's/[[:digit:]]//g')"

        if [[ ! -z $nodigits ]] ; then

            print "Invalid number format! Only digits, no commas, spaces, etc." 

        fi 
    fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM