免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1677 | 回复: 4
打印 上一主题 下一主题

刚发现一个有趣的问题(bash) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-06-09 13:30 |只看该作者 |倒序浏览
本帖最后由 seeLnd 于 2010-06-09 13:35 编辑

一直以来,我都以为

if [ a = b ]; then
   cmds
fi

[ a = b ] && cmds

这二者都没什么区别的,
可是分别你执行一下,他们各自的 $?  是不一样的,前者总是返回 0,  不会根据条件的真假,来返回相应值,除非语法错误另说。

我想可能是关键字if 有什么特殊规定吧,
或者也可能是
前者我们看到的是if ...  fi 这个语句块的返回值,只要没语法错误,if ... fi体内语句没有被执行的话,它规定总是返回0,
而后者我们看到的是  [ 这个命令的返回值,它的规定就是条件不符或者参数错误,都会返回非0。

大家也来分析下吧。

论坛徽章:
0
2 [报告]
发表于 2010-06-09 13:39 |只看该作者
这样说也许更清楚,
if ...  fi 不是返回 条件 真假的值,而是返回 if ...  fi 体内的命令执行结果的返回值,如果没有任何命令被执行,那么总是返回 0

论坛徽章:
0
3 [报告]
发表于 2010-06-09 14:29 |只看该作者
学习

论坛徽章:
0
4 [报告]
发表于 2010-06-09 14:36 |只看该作者
本帖最后由 kala_fly 于 2010-06-09 14:38 编辑


    if list; then list; [ elif list; then list; ] ... [ else list; ] fi

              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.



[list=2]
test

Exit with the status determined by EXPRESSION.Exit with the status determined by EXPRESSION.

论坛徽章:
0
5 [报告]
发表于 2010-06-09 14:37 |只看该作者
{:3_182:}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP