雜集:淺談Linux中腳本第一行 " !

實在抱歉,由於頭條標題限制#的出現,所以在這兒聲明一下。

Linux中#!/bin/bash和#!/bin/sh的區別

1、

#!/bin/sh:

指此腳本使用/bin/sh來解釋執行,#!是特殊的表示符,其後面跟的是此解釋此腳本的shell的路徑。

#!/bin/bash:

指此腳本使用/bin/bash來解釋執行,#!是特殊的表示符,其後面跟的是此解釋此腳本的shell的路徑。

補充:

系統支持的shell格式

雜集:淺談Linux中腳本第一行

2、

man sh

雜集:淺談Linux中腳本第一行

man bash

雜集:淺談Linux中腳本第一行

執行man bash、man sh解釋是完全一樣的。

官方解釋如下:

DESCRIPTION

Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh).

Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.1). Bash can be configured to be POSIX-conformant by default.

Google翻譯如下:

Bash是一種兼容sh的命令語言解釋器,它執行從標準輸入或文件讀取的命令。Bash還包含了Korn和C shell(ksh和csh)的有用功能。

Bash旨在成為IEEE POSIX規範(IEEE標準1003.1)的Shell和Utilities部分的一致實現。 默認情況下,Bash可以配置為符合POSIX標準。

3、

從一個案例感受一下兩者的區別

3.1、

新建一個demo.sh腳本

寫入

#!/bin/sh

source nonExistent.sh #nonExistent.sh實際並不存在

echo "hello,demo.sh"

雜集:淺談Linux中腳本第一行

3.2、

執行./demo.sh

提示沒有文件

即:

source不成功,不會運行source後面的代碼

雜集:淺談Linux中腳本第一行

3.3、

修改腳本--改為bash解析

#!/bin/bash

source nonExistent.sh #nonExistent.sh實際並不存在

echo "hello,demo.sh"

雜集:淺談Linux中腳本第一行

3.4、

執行./demo.sh

提示文件錯誤

但是執行了下一句的echo "hello,demo.sh"

雜集:淺談Linux中腳本第一行

3.5、

指定sh 打開demo.sh

提示文件錯誤

無打印

雜集:淺談Linux中腳本第一行

解釋:

1、sh一般設成bash的軟鏈接

雜集:淺談Linux中腳本第一行

2、 在linux系統當中,使用sh調用執行腳本相當於打開了bash的POSIX標準模式。

即:

/bin/sh 相當於 /bin/bash --posix

那麼,sh跟bash的區別,實際上就是bash有沒有開啟posix模式的區別。

3、

我們把/bin/sh改成/bin/bash --posix測試一下

#!/bin/bash --posix

source nonExistent.sh #nonExistent.sh實際並不存在

echo "hello,demo.sh"

雜集:淺談Linux中腳本第一行

./demo.sh

雜集:淺談Linux中腳本第一行

和#!/bin/sh一樣

測試完成

歡迎大家給予寶貴的意見或者建議。

歡迎大家補充或者共享一些其他的方法。

感謝支持。


分享到:


相關文章: