当我在2009年作为arg传递给这个shell函数时,它返回0,为什么?
isyear()
{
case $arg in
[0-9][0-9][0-9][0-9]) NUM=1 ;;
*) NUM=0 ;;
esac
echo $arg
}
答案 0 :(得分:2)
您可能意味着$1
而不是$arg
。 $arg
未在任何地方定义,$1
是函数的第一个参数。
答案 1 :(得分:1)
您的意思是使用return
代替echo
吗?
return [n] Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body.
答案 2 :(得分:0)
没关系,它应该是$ 1而不是$ arg和echo $ NUM。
答案 3 :(得分:0)
两个拼写错误: 首先,你需要使用$ 1而不是$ arg来获取函数的第一个参数。 其次,我认为你的意思是回应$ NUM而不是传入的参数!
isyear() {
case $1 in
[0-9][0-9][0-9][0-9]) NUM=1 ;;
*) NUM=0 ;;
esac
echo $NUM
}
你也可以考虑像这样重做:
#!/bin/bash
isyear() {
case $1 in
[0-9][0-9][0-9][0-9]) return 1 ;;
*) return 0 ;;
esac
}
isyear cheese
if [ "$?" -eq "1" ]; then
echo "Yes, it is a year!"
else
echo "Darn!"
fi
isyear 2009
if [ "$?" -eq "1" ]; then
echo "Yes, it is a year!"
else
echo "Darn!"
fi