免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: yonka
打印 上一主题 下一主题

[其他] 对shell中命令执行成功返回值的疑问 [复制链接]

论坛徽章:
0
11 [报告]
发表于 2012-08-16 10:38 |只看该作者
回复 9# seesea2517


    理解。谢谢

无论true是常量0还是执行结果为0的命令,其实效果都一样对吧。也即命令执行成功的实际返回值是0。

我不太理解的是对if(命令)的判断,shell对if的条件的解释也与其他语言不同吗?if(0)表示符合条件?

论坛徽章:
0
12 [报告]
发表于 2012-08-16 10:56 |只看该作者
回复 6# yonka
  1. personball@vostro:~$./iftest.sh
  2. 0 -lt 1
  3. 0
  4. true
  5. 1 -lt 0
  6. 1
  7. false
  8. personball@vostro:~$cat iftest.sh
  9. #!/bin/bash
  10. #FileName:
  11. #Author:
  12. #Date:

  13. echo "0 -lt 1"
  14. if [ 0 -lt 1 ]
  15. then
  16.         echo $?
  17.         echo "true"
  18. else
  19.         echo $?
  20.         echo "false"
  21. fi

  22. echo "1 -lt 0"
  23. if [ 1 -lt 0 ]
  24. then
  25.         echo $?
  26.         echo "true"
  27. else
  28.         echo $?
  29.         echo "false"
  30. fi

  31. exit 0
  32. personball@vostro:~$
复制代码

论坛徽章:
0
13 [报告]
发表于 2012-08-16 11:05 |只看该作者
回复 12# personball


    谢谢热心的朋友!

你这个脚本示范是为了说明shell中的if其实是当内容为0时表示符合,执行then;而为1的时候表示不符合,执行else对吗?

论坛徽章:
0
14 [报告]
发表于 2012-08-16 11:08 |只看该作者
回复 13# yonka


    其实吧,我觉得不用管if里的条件到底返回啥,你只要知道 -lt是less then ,成立时自然去then那边,不成立时去else那边,何必管if条件里的返回值?

论坛徽章:
8
摩羯座
日期:2014-11-26 18:59:452015亚冠之浦和红钻
日期:2015-06-23 19:10:532015亚冠之西悉尼流浪者
日期:2015-08-21 08:40:5815-16赛季CBA联赛之山东
日期:2016-01-31 18:25:0515-16赛季CBA联赛之四川
日期:2016-02-16 16:08:30程序设计版块每日发帖之星
日期:2016-06-29 06:20:002017金鸡报晓
日期:2017-01-10 15:19:5615-16赛季CBA联赛之佛山
日期:2017-02-27 20:41:19
15 [报告]
发表于 2012-08-16 12:31 |只看该作者

  1. if list; then list; [ elif list; then list; ] ... [ else list; ] fi
  2.     The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.
复制代码
if后面是个list,根据list的exit status作分流

论坛徽章:
0
16 [报告]
发表于 2012-08-16 13:31 |只看该作者
回复 15# waker


    谢谢哦,很清楚。看来什么都有解释和定义的呀!

论坛徽章:
0
17 [报告]
发表于 2012-08-16 14:55 |只看该作者
yonka 发表于 2012-08-16 08:36
回复 2# waker

并不是所有的语言都是1表示true的

论坛徽章:
0
18 [报告]
发表于 2012-08-16 15:16 |只看该作者
各个语言都不一样 ,shell用-eq -gt比较数字,而perl用 -eq -gt 比较字符串。我晕死。

论坛徽章:
3
处女座
日期:2014-11-05 11:02:4315-16赛季CBA联赛之四川
日期:2015-12-10 14:37:4015-16赛季CBA联赛之天津
日期:2017-09-08 18:39:34
19 [报告]
发表于 2012-08-16 23:52 |只看该作者
回复 5# waker


   
1表示true 2表示true 100表示true,0表示false
实际的情况是成功只有一种,失败的状态很多,请问你只有0这一种false如何去区分失败的状态?


精辟
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP