我有一个脚本,在其中我调用一个函数。如何使用函数的退出状态来打印消息,而不将消息合并到函数中?
我应该编写一个包含以下内容的脚本:
您的脚本应包含使用三个参数的函数increasingNos
。所有三个参数都应该是整数。如果正好有三个参数并且它们是按递增顺序排列的数字,则该功能是“成功”(退出状态为0)。如果有三个参数但是它们的顺序不是递增,则该函数的退出状态应为1。如果参数少于或多于3,则该函数的退出状态应为2。
和...
你应该在>强调increasingNos
之后用参数17 5 23打印一个适当的信息到标准输出来说明是否有三个参数以及它们是否是增加的数字订购。使用if
条件和函数调用的退出状态来执行此操作。此if
条件可能不位于函数increaseNos。
这就是我的想法;每当我运行脚本时,它会在函数调用达到退出状态时退出。如何执行脚本的其余部分?
increasingNos(){
if [ $# -ne 3 ];then
exit 2
fi
if [ $1 -ge $2 ] || [ $2 -ge $3 ];then
exit 1
else
exit 0
fi
}
increasingNos 17 5 23
if [ $? -eq 2 ];then
echo "You did not supply exactly 3 integer parameters!"
fi
if [ $? -eq 1 ];then
echo "Your parameters were not input in increasing order!"
fi
if [ $? -eq 0 ];then
echo "Congrats, you supplied 3 integers in increasing order!"
fi
答案 0 :(得分:3)
使用return
代替exit
并将$?
的值保存在变量中,因为它会在第一次测试后发生变化。
这有效:
increasingNos(){
if [ $# -ne 3 ];then
return 2
fi
if [ $1 -ge $2 ] || [ $2 -ge $3 ];then
return 1
else
return 0
fi
}
increasingNos 17 5 23
stat=$?
if [ $stat -eq 2 ];then
echo "You did not supply exactly 3 integer parameters!"
fi
if [ $stat -eq 1 ];then
echo "Your parameters were not input in increasing order!"
fi
if [ $stat -eq 0 ];then
echo "Congrats, you supplied 3 integers in increasing order!"
fi
答案 1 :(得分:2)
您需要在函数中使用return
而不是exit
。