Yinon
Yinon

Reputation: 955

Shell script running different on MacOS and Linux

I'm trying to run my shell script on Linux (Ubuntu).
It's running correctly on MacOS, but on Ubuntu it doesn't.

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

Ubuntu output this error for running: sh myScript.sh:

Syntax error: end of file unexpected (expecting "do")
  1. Why is there any difference between them, since both of them are running by Bash? How can I avoid future errors caused by their differences?
  2. I tried cat yourscript.sh | tr -d '\r' >> yournewscript.sh as related question was suggested to do, and also while [ true ]. The command hexdump -C util/runner.sh result is:

    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
    

Upvotes: 3

Views: 1792

Answers (1)

Michael
Michael

Reputation: 6517

The shebang #! line at the top of your file tells that this is a bash script. But then you run your script with sh myScript.sh, therefore using the sh shell.

The sh shell is not the same as the bash shell in Ubuntu, as explained here.

To avoid this problem in the future, you should call shell scripts using the shebang line. And also make sure to prefer bash over sh, because the bash shell is more convenient and standardized (IMHO). In order for the script to be directly callable, you have to set the executable flag, like this:

chmod +x yournewscript.sh

This has to be done only once (it's not necessary to do this on every call.)

Then you can just call the script directly:

./yournewscript.sh

and it will be interpreted by whatever command is present in the first line of the script.

Upvotes: 6

Related Questions