簡體   English   中英

Shell腳本在MacOS和Linux上運行不同

[英]Shell script running different on MacOS and Linux

我正在嘗試在Linux(Ubuntu)上運行Shell腳本。
它可以在MacOS上正常運行,但不能在Ubuntu上運行。

#!/usr/bin/env bash
while true
do
   node Client/request -t 10.9.2.4 -p 4400 --flood
done

Ubuntu輸出以下錯誤以運行:sh myScript.sh:

Syntax error: end of file unexpected (expecting "do")
  1. 由於它們都是由Bash運行,為什么它們之間有什么區別? 如何避免由於它們的差異而導致的未來錯誤?
  2. 我試過cat yourscript.sh | tr -d '\\r' >> yournewscript.sh cat yourscript.sh | tr -d '\\r' >> yournewscript.sh作為相關問題,同時建議使用while [ true ] 命令hexdump -C util/runner.sh結果為:

     00000000 23 21 2f 75 73 72 2f 62 69 6e 2f 65 6e 76 20 62 |#!/usr/bin/env b| 00000010 61 73 68 0d 0a 0d 0a 77 68 69 6c 65 20 5b 20 74 |ash....while [ t| 00000020 72 75 65 20 5d 0d 0a 64 6f 0d 0a 20 20 20 6e 6f |rue ]..do.. no| 00000030 64 65 20 43 6c 69 65 6e 74 2f 72 65 71 75 65 73 |de Client/reques| 00000040 74 20 2d 74 20 31 39 32 2e 31 36 38 2e 30 2e 34 |t -t 192.168.0.4| 00000050 31 20 2d 70 20 34 34 30 30 20 2d 2d 66 6c 6f 6f |1 -p 4400 --floo| 00000060 64 0d 0a 64 6f 6e 65 0d 0a |d..done..| 00000069 

社bang #! 文件頂部的一行表明這是一個bash腳本。 但是,然后使用sh myScript.sh運行腳本,因此使用sh shell。

sh shell與Ubuntu中的bash shell不同,如此處所述

為避免將來出現此問題,應使用shebang行調用shell腳本。 並且還要確保更喜歡bash而不是sh ,因為bash shell更加方便和標准化(IMHO)。 為了使腳本可直接調用,必須設置可執行標志,如下所示:

chmod +x yournewscript.sh

此操作只需執行一次(不必在每次調用時都執行此操作。)

然后,您可以直接調用腳本:

./yournewscript.sh

它將由腳本第一行中出現的任何命令來解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM