翼度科技»论坛 云主机 LINUX 查看内容

Shell函数练习

11

主题

11

帖子

33

积分

新手上路

Rank: 1

积分
33
1. 编写函数,实现打印绿色OK和红色FAILED 判断是否有参数,存在为Ok,不存在为FAILED
  1. [root@template shellScript]# cat ex1.sh
  2. # 编写函数,实现打印绿色OK和红色FAILED 判断是否有参数,存在为Ok,不存在为FAILED
  3. #!/bin/bash
  4. fun(){
  5. if [ $# -ne 0 ]
  6. then
  7.         echo -e "\033[32m OK \033[0m"
  8. else
  9.         echo -e "\033[31m FAILED \033[0m"
  10. fi
  11. }
  12. read -p "plz input sth..." str
  13. fun $str
  14. [root@template shellScript]# ./ex1.sh
  15. plz input sth...1qw11d1d
  16. OK
  17. [root@template shellScript]# ./ex1.sh
  18. plz input sth...
  19. FAILED
复制代码
运行效果图:

2. 编写函数,实现判断是否无位置参数,如无参数,提示错误
  1. [root@template shellScript]# cat ex2.sh
  2. # 编写函数,实现判断是否无位置参数,如无参数,提示错误
  3. #!/bin/bash
  4. fun() {
  5.   if [ $# -eq 0 ]
  6.   then
  7.     echo "无位置参数"
  8.   else
  9.     echo "位置参数为$@"
  10.   fi
  11. }
  12. read -p "plz input sth..." str
  13. fun $str
复制代码
运行截图:

3. 编写函数实现两个数字做为参数,返回最大值
  1. # 此方法不能比较负数的大小
  2. [root@template shellScript]# cat ex3.sh
  3. # 编写函数实现两个数字做为参数,返回最大值
  4. #!/bin/bash
  5. fun(){
  6. # 判断输入是否是数字
  7. if [[ $a =~ ^[0-9]*$ ]] && [[ $b =~ ^[0-9]*$ ]]
  8. then
  9.         # 比较大小
  10.         if [ $a -gt $b ]
  11.         then
  12.                 echo "$a > $b"
  13.         elif [ $a -lt $b ]
  14.         then
  15.                 echo "$a < $b"
  16.         else
  17.                 echo "$a = $b"
  18.         fi
  19. else
  20.         echo "请输入俩个数字!!!"
  21. fi
  22. }
  23. # 输入负数也可以比较大小
  24. # read -p "plz input two num:" a b
  25. read -p "plz input num1:" a
  26. read -p "plz input num2:" b
  27. fun $a $b
复制代码
测试截图:

方式二:
  1. [root@template shellScript]# cat ./ex3_2.sh
  2. #!/bin/bash
  3. read -p "please input two number:" a b
  4. fun(){
  5. [ -z "$a" -o -z "$b" ] && {
  6. echo "please input 'two' number"
  7. exit 1
  8. }
  9. expr $a + 10 &>/dev/null
  10. return_a=$?
  11. expr $b + 10 &>/dev/null
  12. return_b=$?
  13. [ "$return_a" -eq 0 -a "$return_b" -eq 0 ] || {
  14. echo "please input two 'number'"
  15. exit 2
  16. }
  17. [ "$a" -lt "$b" ] && {
  18. echo "$a < $b"
  19. exit 0
  20. }
  21. [ "$a" -eq "$b" ] && {
  22. echo "$a = $b"
  23. exit 0
  24. }
  25. [ "$a" -gt "$b" ] && {
  26. echo "$a > $b"
  27. exit 0
  28. }
  29. }
  30. fun $a $b
复制代码
运行截图:

出处:http://www.cnblogs.com/sre-chan/-------------------------------------------
个性签名:今天做了别人不想做的事,明天你就做得到别人做不到的事,尝试你都不敢,你拿什么赢!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

来源:https://www.cnblogs.com/sre-chan/p/17278868.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具