您的位置:首页 > 运维架构 > Shell

shell脚本实例 使用exit语句和if

2009-11-26 17:36 991 查看
使用exit语句和if 。exit它使整个脚本中止运行。最常使用于来自用户输入的不正确请求,比如一条语句没有成功运行或者某些其他错误发生。 exit 语句可以带一个可选参数。参数是一个整数退出状态码,储存在 $? 中的返回给父进程的退出状态码。 0参数意味着脚本成功运行完毕。程序员会用其他值来给父进程传递不同的消息,所以根据子进程的成功或者失败,父进程采取不同的动作。如果没有参数给 exit 语句,父shell使用 $? 变量的现存值。
下面是一个和 penguin.sh 脚本相似的例子,会对 feed.sh 传回一个退出状态
penguin.sh
#!/bin/bash
# This script lets you present different menus.He will only be happy
# when given a fish. We've also added a dolphin and (presumably) a camel.
if [ "$menu" == "fish" ]; then
if [ "$animal" == "penguin" ]; then
echo "i'm penguin,that's good,i like fish,get more!!!"
elif [ "$animal" == "dolphin" ]; then
echo "i'm dolphin,i'm not like fish"
else
echo "*what?other*"
fi
else
if [ "$animal" == "penguin" ]; then
echo "what you give is not fish,i want fish!quickly"
exit 1
elif [ "$animal" == "dolphin" ]; then
echo "i am dolphin,not like this too,fish!!!"
exit 2
else
echo "Will you read this sign?!"
exit 3
fi
fi
--------------------------------------------------------------------
feed.sh

#!/bin/bash
# This script acts upon the exit status given by penguin.sh
export menu="$1"
export animal="$2"
feed="/jiaoben/penguin.sh"
$feed $menu $animal
case $? in
1)
echo "Guard: You'd better give'm a fish, less they get violent..."
;;
2)
echo "Guard: It's because of people like you that they are leaving earth all the time..."
;;
3)
echo "Guard: Buy the food that the Zoo provides for the animals, you ***, how do you think we survive?"
;;
*)
echo "Guard: Don't forget the guide!"
;;
esac
-------------------------
执行情况:
# ./feed.sh fish dolphin
i'm dolphin,i'm not like fish
Guard: Don't forget the guide!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  实例 脚本 shell