有些時候我們需要驗證腳本的參數或某些變量的值是否爲數字,如果不是則需要需要給出提示,並退出腳本。
[root@xieqichao ~]# cat > test3.sh
#!/bin/sh
#1. $1是腳本的第一個參數,這裏作爲awk命令的第一個參數傳入給awk命令。
#2. 由於沒有輸入文件作爲輸入流,因此這裏只是在BEGIN塊中完成。
#3. 在awk中ARGV數組表示awk命令的參數數組,ARGV[0]表示命令本身,ARGV[1]表示第一個參數。
#4. match是awk的內置函數,返回值爲匹配的正則表達式在字符串中(ARGV[1])的起始位置,沒有找到返回0。
#5. 正則表達式的寫法已經保證了匹配的字符串一定是十進制的正整數,如需要浮點數或負數,僅需修改正則即可。
#6. awk執行完成後將結果返回給isdigit變量,並作爲其初始化值。
#7. isdigit=`echo $1 | awk '{ if (match($1, "^[0-9]+$") != 0) print "true"; else print "false" }' `
#8. 上面的寫法也能實現該功能,但是由於有多個進程參與,因此效率低於下面的寫法。
isdigit=`awk 'BEGIN { if (match(ARGV[1],"^[0-9]+$") != 0) print "true"; else print "false" }' $1`
if [[ $isdigit == "true" ]]; then
echo "This is numeric variable."
number=$1
else
echo "This is not numeric variable."
number=0
fi
CTRL+D
[root@xieqichao ~]# ./test3.sh 12
This is numeric variable.
[root@xieqichao ~]# ./test3.sh 12r
This is not numeric variable.