Linux sh script throws "#!/bin/sh: not found"

Your script starts with:

#!/bin/sh

This is not a comment, but a shebang to tell your operating system to use /bin/sh to execute the script. But apparently Ubuntu cannot find it.

  • If ls /bin/sh shows no result, then I guess that needs to be fixed. As a temporary solution, you might be lucky that your script also works with, for example, bash:

    #!/bin/bash
    
  • If /bin/sh does exist (like it should), then somehow Ubuntu cannot interpret that first line. Dump it as hex:

    head -n 1 myscript.sh | hexdump -C
    
    00000000  ef bb bf 23 21 2f 62 69  6e 2f 73 68 0d 0a        |...#!/bin/sh..|
    

    And with the result:

    • Make sure line endings are using the Unix format, LF (\n or hexadecimal 0a) instead of, for example, the Windows standard CRLF (\r\n or hexadecimal 0d0a in the example above). On a Mac this would actually throw a different error:

      /bin/sh^M: bad interpreter: No such file or directory
      
    • Make sure file encodings do not mess up, such as an (invisible) Unicode BOM (ef bb bf in the example output above). In the above example your shell is not seeing a comment or the shebang, but is trying to run a command that starts with 3 invisible characters. In this case your shell would probably still execute the next lines, or might even complete the script successfully. On a Mac the first line actually throws:

      ./myscript.sh: line 1: #!/bin/sh: No such file or directory
      

To dump the error message to see the invisible characters in that message, one needs to redirect the error output to the standard output:

./myscript.sh 2>&1 | hexdump -C

00000000  2e 2f 6d 79 73 63 72 69  70 74 2e 73 68 3a 20 6c  |./myscript.sh: l|
00000010  69 6e 65 20 31 3a 20 ef  bb bf 23 21 2f 62 69 6e  |ine 1: ...#!/bin|
00000020  2f 73 68 3a 20 4e 6f 20  73 75 63 68 20 66 69 6c  |/sh: No such fil|
00000030  65 20 6f 72 20 64 69 72  65 63 74 6f 72 79 0a     |e or directory.|