Nic*_*nay 94 bash executable shell-script shebang
我已经创建了一个 bash 脚本,但是当我尝试执行它时,我得到
#!/bin/bash no such file or directory
Run Code Online (Sandbox Code Playgroud)
我需要运行命令:bash script.sh
让它工作。
我怎样才能解决这个问题?
jll*_*gre 125
这种消息通常是由于虚假的shebang行,第一行末尾的额外回车或开头的BOM。
跑:
$ head -1 yourscript | od -c
Run Code Online (Sandbox Code Playgroud)
看看它是如何结束的。
这是错误的:
0000000 # ! / b i n / b a s h \r \n
Run Code Online (Sandbox Code Playgroud)
这也是错误的:
0000000 357 273 277 # ! / b i n / b a s h \n
Run Code Online (Sandbox Code Playgroud)
这是对的:
0000000 # ! / b i n / b a s h \n
Run Code Online (Sandbox Code Playgroud)
如果这是问题,请使用dos2unix
(或sed
, tr
, awk
, perl
, python
...) 修复您的脚本。
这是一个将同时删除 BOM 和尾随 CR 的方法:
sed -i '1s/^.*#//;s/\r$//' brokenScript
Run Code Online (Sandbox Code Playgroud)
以下是三个脚本,仅显示它们的名称 ( echo $0
) 并具有以下各自的 shebang 行:
正确的脚本:
0000000 # ! / b i n / b a s h \n
Run Code Online (Sandbox Code Playgroud)
scriptWithBom:
0000000 357 273 277 # ! / b i n / b a s h \n
Run Code Online (Sandbox Code Playgroud)
带CRLF的脚本:
0000000 # ! / b i n / b a s h \r \n
Run Code Online (Sandbox Code Playgroud)
在 bash 下,运行它们将显示以下消息:
$ ./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
Run Code Online (Sandbox Code Playgroud)
通过显式调用解释器来运行伪造的脚本可以让 CRLF 脚本毫无问题地运行:
$ bash ./scriptWithCRLF
./scriptWithCRLF
$ bash ./scriptWithBom
./scriptWithBom: line 1: #!/bin/bash: No such file or directory
./scriptWithBom
Run Code Online (Sandbox Code Playgroud)
这是在 下观察到的行为ksh
:
$ ./scriptWithCRLF
ksh: ./scriptWithCRLF: not found [No such file or directory]
$ ./scriptWithBom
./scriptWithBom[1]: #!/bin/bash: not found [No such file or directory]
./scriptWithBom
Run Code Online (Sandbox Code Playgroud)
和下dash
:
$ ./scriptWithCRLF
dash: 2: ./scriptWithCRLF: not found
$ ./scriptWithBom
./scriptWithBom: 1: ./scriptWithBom: #!/bin/bash: not found
./scriptWithBom
Run Code Online (Sandbox Code Playgroud)
moe*_*eye 12
实际上,bash 脚本的正确shebang 是这样的:
#!/usr/bin/env bash
Run Code Online (Sandbox Code Playgroud)
因为,在 freeBSD 中,bash 位于 /usr/local/bin/bash
cwa*_*ash 11
如果存在这两个问题,您可以使用 vi 来解决它们:
vi <your_file>
:set ff=unix
:set nobomb
:wq
Run Code Online (Sandbox Code Playgroud)