Re: [問題] bash 與 ./ 執行 script 差異

看板Linux作者 (System hacked)時間2年前 (2021/10/16 23:29), 編輯推噓6(608)
留言14則, 6人參與, 2年前最新討論串2/2 (看更多)
※ 引述《scitamehtam (scitamehtam)》之銘言: : 想請問我寫了一個 shell script : 然後用 bash 去執行 : 跟用 ./ 去執行 : 在系統上是否有差異呢? : 謝謝! 推文有人提到 shebang 了,這邊在等 D2R 順便加減賺一下 P 幣... 首先是 bash ooxx.sh 的方式,這是強制用 bash 跑,第一行的 #!/bin/bash 或是 #!/bin/sh 會被當成註解,裡面剩下的行數會當作 bash 指令來跑。 舉例來說,弄一個 test.sh,裡面加上 bash -x (把執行的指令列出來): gslin@home [/tmp] [23:06/W7] cat test.sh #!/bin/bash -x echo $0 用 bash test.sh 跑會出現: gslin@home [/tmp] [23:06/W7] bash test.sh test.sh 但你直接跑他則會吃 #!/bin/bash -x 這邊的參數: gslin@home [/tmp] [23:07/W7] ./test.sh + echo ./test.sh ./test.sh 在維基百科有說明什麼是 shebang (也就是第一行的 #!): https://zh.wikipedia.org/wiki/Shebang https://en.wikipedia.org/wiki/Shebang_(Unix) 另外 shebang 也有一些限制,像是大多數支援 shebang 的作業系統下,#! 那行不 能超過 127 chars: https://stackoverflow.com/questions/10813538/shebang-line-limit-in-bash-and-linux-kernel 直接在 command line 下用 bash 跑的話,可以塞的參數就大多了。 -- Resistance is futile. https://blog.gslin.org/ & <gslin@gslin.org> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.34.121.114 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Linux/M.1634398189.A.1FE.html

10/17 11:46, 2年前 , 1F
其他就雖然這邊是 Linux 板,但建議 bash, zsh 之類的
10/17 11:46, 1F

10/17 11:47, 2年前 , 2F
shebang 還是寫成 #!/usr/bin/env bash 之類的更通用
10/17 11:47, 2F

10/17 12:52, 2年前 , 3F
還有一個小區別就是: bash file的話,
10/17 12:52, 3F

10/17 12:52, 2年前 , 4F
不需要chomd +x file, 就能執行.
10/17 12:52, 4F

10/17 17:15, 2年前 , 5F
感謝推文和PO文的兩位 以前還真的沒特別想到底有什麼差別
10/17 17:15, 5F

10/17 20:31, 2年前 , 6F
謝謝大家討論與分享~
10/17 20:31, 6F

10/17 20:58, 2年前 , 7F
python也是寫#!/usr/bin/env python來套用venv裡的直譯器
10/17 20:58, 7F

10/17 22:16, 2年前 , 8F
謝謝顧及 OpenBSD(bash 在 /usr/local/bin),不過,
10/17 22:16, 8F

10/17 22:16, 2年前 , 9F
只是舉例說明,是還好。
10/17 22:16, 9F

10/17 22:21, 2年前 , 10F
還有一個大區別, 鳥哥有講: http://goo.gl/eQzWM
10/17 22:21, 10F

10/17 22:30, 2年前 , 11F
抱歉, 上面那個網址是跟source才有關.
10/17 22:30, 11F

10/17 23:01, 2年前 , 12F
在 bash 而言,source 和 ./ 是一樣的。其他的 shell
10/17 23:01, 12F

10/17 23:02, 2年前 , 13F
要看是怎麼 implement。POSXI 並沒嚴格限制。
10/17 23:02, 13F

10/17 23:07, 2年前 , 14F
不是 ./ 是指 . 。
10/17 23:07, 14F
文章代碼(AID): #1XQk_j7- (Linux)
文章代碼(AID): #1XQk_j7- (Linux)