作者:
DarkKiller (System hacked)
2021-10-16 23:29:45※ 引述《scitamehtam (scitamehtam)》之銘言:
: 想請問我寫了一個 shell script
: 然後用 bash 去執行
: 跟用 ./ 去執行
: 在系統上是否有差異呢?
: 謝謝!
推文有人提到 shebang 了,這邊在等 D2R 順便加減賺一下 P 幣...
首先是 bash ooxx.sh 的方式,這是強制用 bash 跑,第一行的 #!/bin/bash 或是
#!/bin/sh 會被當成註解,裡面剩下的行數會當作 bash 指令來跑。
舉例來說,弄一個 test.sh,裡面加上 bash -x (把執行的指令列出來):
[email protected] [/tmp] [23:06/W7] cat test.sh
#!/bin/bash -x
echo $0
用 bash test.sh 跑會出現:
[email protected] [/tmp] [23:06/W7] bash test.sh
test.sh
但你直接跑他則會吃 #!/bin/bash -x 這邊的參數:
[email protected] [/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 跑的話,可以塞的參數就大多了。
其他就雖然這邊是 Linux 板,但建議 bash, zsh 之類的shebang 還是寫成 #!/usr/bin/env bash 之類的更通用
還有一個小區別就是: bash file的話,不需要chomd +x file, 就能執行.
作者:
hms5232 (未)
2021-10-17 17:15:00感謝推文和PO文的兩位 以前還真的沒特別想到底有什麼差別
作者:
Adama (So Say We All.)
2021-10-17 20:58:00python也是寫#!/usr/bin/env python來套用venv裡的直譯器
謝謝顧及 OpenBSD(bash 在 /usr/local/bin),不過,只是舉例說明,是還好。
在 bash 而言,source 和 ./ 是一樣的。其他的 shell要看是怎麼 implement。POSXI 並沒嚴格限制。不是 ./ 是指 . 。