Chinaunix首页 | 论坛 | 博客
  • 博客访问: 298271
  • 博文数量: 240
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2016-08-04 18:14
文章分类

全部博文(240)

文章存档

2017年(8)

2014年(4)

2013年(15)

2012年(4)

2011年(14)

2010年(55)

2009年(140)

我的朋友

分类: LINUX

2013-10-12 10:28:02

大家都知道,sh 是 bash 的一个软链接,可是有时候,用 bash 可以执行成功的脚本用 sh 执行却会报错,这是为什么呢?

例如当shell 脚本第一行采用下面这两张写法的时候效果有时是不尽相同的。
#!/bin/sh
#!/bin/bash


先看看环境:

  1. [user@host ~]$ which sh bash
  2. /usr/local/bin/sh
  3. /usr/local/bin/bash
  4. [user@host ~]$ ls -l /usr/local/bin/sh /usr/local/bin/bash
  5. lrwxrwxrwx 1 root root 9 Sep 21 2012 /usr/local/bin/bash -> /bin/bash
  6. lrwxrwxrwx 1 root root 7 Sep 21 2012 /usr/local/bin/sh -> /bin/sh



举一个例子:

  1. [user@host ~]$ cat test.sh
  2. # myfile.sh dosn't exst!
  3. source myfile.sh
  4. echo hello

  5. [user@host ~]$ sh test.sh
  6. test.sh: line 2: myfile.sh: No such file or directory

  7. [user@host ~]$ bash test.sh
  8. test.sh: line 2: myfile.sh: No such file or directory
  9. hello





另外一个例子:
  1. [user@host ~]$ cat test.sh
  2. while read i;do
  3.     echo "+++"$i"+++"
  4. done< <(ls -1 /var/log/sa)


  5. [user@host ~]$ sh test.sh
  6. test.sh: line 3: syntax error near unexpected token `<'
  7. test.sh: line 3: `done< <(ls -1 /var/log/sa)'


  8. [user@host ~]$ bash test.sh
  9. +++sa04+++
  10. +++sa05+++
  11. +++sa06+++
  12. +++sa07+++
  13. +++sa08+++
  14. +++sa09+++
  15. +++sa10+++


第一个例子中,很明显可以看到,当使用 sh 执行时,如果第一行执行失败,则脚本退出,而使用 bash 执行时虽然第一行失败,但脚本仍然会继续向下执行;
第二个例子则是语法是否支持的问题,当使用 sh 执行时,会报一个预发错误,而 bash 执行时则正常;


原因说明:
1)一般 linux 系统默认 sh 都是 bash 的软连接: /bin/sh -> bash
2)一般的linux系统当中(如redhat),使用sh调用执行脚本相当于打开了bash的POSIX标准模式,也就是说 /bin/sh 相当于 /bin/bash --posix
3)--posix   Change  the  behavior  of  bash where the default operation differs from the POSIX standard to match the standard (posix mode).

POSIX,全称为可移植性操作系统接口,是一种关于信息技术的IEEE标准。它包括了系统应用程序接口(简称API),以及实时扩展[C语言]。
该标准的目的是定义了标准的基于UNIX操作系统的系统接口和环境来支持源代码级的可移植性。现在,标准主要提供了依赖C语言的一系列标准服务,再将来的版本中,标准将致力于提供基于不同语言的规范。

参考:http://blog.csdn.net/novagx/article/details/2077561
阅读(816) | 评论(0) | 转发(0) |
0

上一篇:编码问题

下一篇:如何查看磁盘是否 ssd

给主人留下些什么吧!~~