当前位置: 技术问答>linux和unix
关于linux下的test问题
来源: 互联网 发布时间:2016-10-16
本文导语: 我写了一段inux下的shell代码如下: #!/bin/sh COUNTER=100 user want to change the value echo "Enter a sensible value:" read VALUE # simple test to see if it is numeric, and add number to value # then checkout return expr $VALUE+10 >/dev/null 2...
我写了一段inux下的shell代码如下:
#!/bin/sh
COUNTER=100
user want to change the value
echo "Enter a sensible value:"
read VALUE
# simple test to see if it is numeric, and add number to value
# then checkout return
expr $VALUE+10 >/dev/null 2>&1
STATUS=$?
# check return code of the expr
if test -z $VALUE || test $STATUS != "0"
then
# send errors
echo "You either entered nothing or a non-numeric."
echo "Sorry, now exiting. Counter stays at $COUNTER."
exit 1
fi
# it is a number, add it to COUNTER
COUNTER=`expr $COUNTER + $VALUE`
echo "Now counter sets to $COUNTER."
结果应该是:输入数字时,为一个结果;输入字母或不输入时,为一个结果。
可是现在却成了:输入数字或字母时,为一个结果;不输入时,为一个结果。
请教大侠,这个脚本哪里有问题呀?谢谢!
#!/bin/sh
COUNTER=100
user want to change the value
echo "Enter a sensible value:"
read VALUE
# simple test to see if it is numeric, and add number to value
# then checkout return
expr $VALUE+10 >/dev/null 2>&1
STATUS=$?
# check return code of the expr
if test -z $VALUE || test $STATUS != "0"
then
# send errors
echo "You either entered nothing or a non-numeric."
echo "Sorry, now exiting. Counter stays at $COUNTER."
exit 1
fi
# it is a number, add it to COUNTER
COUNTER=`expr $COUNTER + $VALUE`
echo "Now counter sets to $COUNTER."
结果应该是:输入数字时,为一个结果;输入字母或不输入时,为一个结果。
可是现在却成了:输入数字或字母时,为一个结果;不输入时,为一个结果。
请教大侠,这个脚本哪里有问题呀?谢谢!
|
其实你的代码 只要改一句就能满足你的要求
把
expr $VALUE+10 >/dev/null 2>&1
改成
expr $VALUE + 10 >/dev/null 2>&1
+号前后应该有空格!!!
把
expr $VALUE+10 >/dev/null 2>&1
改成
expr $VALUE + 10 >/dev/null 2>&1
+号前后应该有空格!!!
|
那你也应该把
COUNTER=`expr $COUNTER + $VALUE`
改成
COUNTER=`expr $COUNTER + $VALUE 2>/dev/null`
|
用ksh吧,用下面的代码判断是否为数字
#!/bin/ksh
if [[ ${VALUE} != +([0-9]) ]];then
echo "invalid digit"
exit 0
fi
#!/bin/ksh
if [[ ${VALUE} != +([0-9]) ]];then
echo "invalid digit"
exit 0
fi
|
你从一开始的想法都是错的 或者说是不合理的
你应该按楼上说的那样 先判断用户输入的是不是数字再进行相应的操作!
|
那汉语描述的让我头晕 执行结果是这样的 看上去各不相同
[root@plesk ~]# ./test.sh
Enter a sensible value:
A
expr: non-numeric argument
Now counter sets to .
[root@plesk ~]# ./test.sh
Enter a sensible value:
You either entered nothing or a non-numeric.
Sorry, now exiting. Counter stays at 100.
[root@plesk ~]# ./test.sh
Enter a sensible value:
15
Now counter sets to 115.
[root@plesk ~]# ./test.sh
Enter a sensible value:
A
expr: non-numeric argument
Now counter sets to .
[root@plesk ~]# ./test.sh
Enter a sensible value:
You either entered nothing or a non-numeric.
Sorry, now exiting. Counter stays at 100.
[root@plesk ~]# ./test.sh
Enter a sensible value:
15
Now counter sets to 115.
|
user want to change the value
前面没有#
前面没有#
|
汗 我以为楼主给敲掉了 我测试的时候自己给补上了