#!/bin/bash - no such file or directory

This kind of message is usually due to a bogus shebang line, either an extra carriage return at the end of the first line or a BOM at the beginning of it.

Run:

$ head -1 yourscript | od -c

and see how it ends.

This is wrong:

0000000   #   !   /   b   i   n   /   b   a   s   h  \r  \n

This is wrong too:

0000000 357 273 277   #   !   /   b   i   n   /   b   a   s   h  \n

This is correct:

0000000   #   !   /   b   i   n   /   b   a   s   h  \n

Use dos2unix (or sed, tr, awk, perl, python…) to fix your script if this is the issue.

Here is one that will remove both of a BOM and tailing CRs:

sed -i '1s/^.*#//;s/\r$//' brokenScript


Note that the shell you are using to run the script will slightly affect the error messages that are displayed.

Here are three scripts just showing their name (echo $0) and having the following respective shebang lines:

correctScript:

0000000   #   !   /   b   i   n   /   b   a   s   h  \n

scriptWithBom:

0000000 357 273 277   #   !   /   b   i   n   /   b   a   s   h  \n

scriptWithCRLF:

0000000   #   !   /   b   i   n   /   b   a   s   h  \r  \n

Under bash, running them will show these messages:

$ ./correctScript
./correctScript
$ ./scriptWithCRLF
bash: ./scriptWithCRLF: /bin/bash^M: bad interpreter: No such file or directory
$ ./scriptWithBom
./scriptWithBom: line 1: #!/bin/bash: No such file or directory
./scriptWithBom

Running the bogus ones by explicitely calling the interpreter allows the CRLF script to run without any issue:

$ bash ./scriptWithCRLF
./scriptWithCRLF
$ bash ./scriptWithBom
./scriptWithBom: line 1: #!/bin/bash: No such file or directory
./scriptWithBom

Here is the behavior observed under ksh:

$ ./scriptWithCRLF
ksh: ./scriptWithCRLF: not found [No such file or directory]
$ ./scriptWithBom
./scriptWithBom[1]: #!/bin/bash: not found [No such file or directory]
./scriptWithBom

and under dash:

$ ./scriptWithCRLF
dash: 2: ./scriptWithCRLF: not found
$ ./scriptWithBom
./scriptWithBom: 1: ./scriptWithBom: #!/bin/bash: not found
./scriptWithBom

This can also be caused by a BOM in a UTF-8 script. If you create the script in Windows sometimes you get some junk at the start of the file.


Actualy, the right shebang for bash script is this:

#!/usr/bin/env bash

Because, in freeBSD, bash is located in /usr/local/bin/bash