在Shell编程中,函数通过return返回其退出状态,0表示无错误,1表示有错误。
在脚本中可以有选择的使用return语句,因为函数在执行完最后一条语句后将执行调用该函数的地方执行后续操作。
示例如下:根据返回值的不同输出不同的结果
#!/bin/bash
#使用return语句的函数
show_week() {
echo -n "What you input is:"
echo "$1"
#根据输入的参数值来显示不同的操作
case $1 in
0)
echo "Sunday"
return 0
;;
1)
echo "Monday"
return 0
;;
2)
echo "Tuesday"
return 0
;;
3)
echo "Wednesday"
return 0
;;
4)
echo "Thursday"
return 0
;;
5)
echo "Friday"
return 0
;;
6)
echo "Saturday"
return 0
;;
*)
return 1
;;
esac
}
#主程序根据返回值不同输出不同的结果
if show_week "$1"
then
echo "You input is Right!"
else
echo "You input is wrong!"
fi
exit 0
脚本运行结果如下:
$ ./test.sh 1
What you input is:1
Monday
You input is Right!
$ ./test.sh 10
What you input is:10
You input is wrong!
$