在MacOS和Linux上运行不同的Shell脚本

Yin*_*non 1 macos bash ubuntu

我正在尝试在Linux(Ubuntu)上运行我的shell脚本.
它在MacOS上运行正常,但在Ubuntu上没有.

#!/usr/bin/env bash
while true
do
   node Client/request -t 10.9.2.4 -p 4400 --flood
done
Run Code Online (Sandbox Code Playgroud)

Ubuntu输出此错误以运行:sh myScript.sh:

Syntax error: end of file unexpected (expecting "do")
Run Code Online (Sandbox Code Playgroud)
  1. 为什么它们之间有任何区别,因为它们都是由Bash运行的?如何避免因差异而导致的未来错误?
  2. 我尝试过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
    
    Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 5

#!文件顶部的shebang 行告诉我这是一个bash脚本.但是然后你运行你的脚本sh myScript.sh,因此使用shshell.

sh外壳是不一样的bashUbuntu的外壳,如这里解释.

为了避免将来出现此问题,您应该使用shebang行调用shell脚本.而且还要确保更喜欢bash over sh,因为bash shell更方便和标准化(恕我直言).为了使脚本可以直接调用,您必须设置可执行标志,如下所示:

chmod +x yournewscript.sh
Run Code Online (Sandbox Code Playgroud)

这必须只进行一次(没有必要在每次通话时都这样做.)

然后你可以直接调用脚本:

./yournewscript.sh
Run Code Online (Sandbox Code Playgroud)

它将由脚本第一行中出现的任何命令解释.