linux -- #!/bin/bash

來源:互聯網
上載者:User

標籤:

#!/bin/bash是指此指令碼使用/bin/bash來解釋執行。其中,#!是一個特殊的表示符,其後,跟著解釋此指令碼的shell路徑。bash只是shell的一種,還有很多其它shell,如:sh,csh,ksh,tcsh,...我們可以通過以下一個樣本來進行實驗,瞭解#!/bin/bash的使用。1)#!/bin/bash只能放在第一行,如果後面還有#!,那麼只能看成是注釋。這裡有三個指令碼(指令碼都要使用”chmod +x  scriptname“命令來獲得可執行許可權):tbash1.sh:#!/bin/shsource abcecho "hello abc" tbash2.sh:#!/bin/bashsource abcecho "hello abc" tbash3.sh:source abcecho "hello abc" 三個指令碼執行的結果:[[email protected] other]$ ./tbash1.sh ./tbash1.sh: line 2: abc: No such file or directory註:當source命令執行有問題時,sh不再往下面執行。[[email protected] other]$ ./tbash2.sh ./tbash2.sh: line 2: abc: No such file or directoryhello abc註:當source命令執行有問題時,bash繼續執行下面命令。[[email protected] other]$ ./tbash3.sh ./tbash3.sh: line 1: abc: No such file or directoryhello abc註:自身登入系統所在的shell是bash。所以,當source命令執行有問題時,bash繼續執行下面命令。 如果將tbash1.sh改成:echo "abc"#!/bin/shsource abcecho "hello abc"那麼,執行結果是:[[email protected] other]$ ./tbash1.sh abc./tbash1.sh: line 3: abc: No such file or directoryhello abc也就是說,指令碼忽略了第二行“#!/bin/sh",直接使用當前所在的shell(也就是bash)來解釋指令碼。 當把tbash1.sh改成:#!/bin/sh#!/bin/bashsource abcecho "hello abc"執行結果為:[[email protected] other]$ ./tbash1.sh ./tbash1.sh: line 3: abc: No such file or directory當執行完source命令時,並沒有往下執行。說明,#!/bin/sh這一行起到作用了,但#!/bin/bash並沒有起作用。在指令碼中,不在第一行的#!/bin/bash,只是一個注釋。 2)#!後面的路徑一定要正確,不正確會報錯。假如,我們把tbash1.sh中第一行的#!後面加了一個不存在的路徑”/home/sh“:#!/home/shsource abcecho "hello abc"執行結果為:[[email protected] other]$ ./tbash1.sh -bash: ./tbash1.sh: /home/sh: bad interpreter: No such file or directory系統會提示/home/sh的路徑不存在。 3)如果一個指令碼在第一行沒有加上#!+shell路徑這一行,那麼,指令碼會預設目前使用者登入的shell,為指令碼解譯器。在1)中,指令碼tbash3.sh的執行結果,就是用當前自己登入的shell(bash)解釋後的結果。我們通常所用的shell都是bash,如果哪天登入到sh,再使用以上類型的指令碼,就會有問題。以下是自己登入到sh下,執行tbash3.sh的結果:-sh-3.2$ ./tbash3.sh ./tbash3.sh: line 1: abc: 沒有那個檔案或目錄與1)中的執行結果是不一樣的。因此,大家應該養成指令碼首行加上#!+shell路徑的習慣。 4)/bin/sh相當於/bin/bash --posix我們將指令碼tbash1.sh改為:#!/bin/bash --posixsource abcecho "hello abc"執行結果:[[email protected] other]$ ./tbash1.sh ./tbash1.sh: line 2: abc: No such file or directory與tbash1.sh原指令碼執行的結果一樣。 我們還可以以tbash3.sh為樣本。用以下命令來執行該指令碼:[[email protected] other]$ bash tbash3.shtbash3.sh: line 1: abc: No such file or directoryhello abc[[email protected] other]$ sh tbash3.sh tbash3.sh: line 1: abc: No such file or directory[[email protected] other]$ bash --posix tbash3.sh tbash3.sh: line 1: abc: No such file or directory "bash tbash3.sh"表示使用bas

linux -- #!/bin/bash

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.