带有注释的Shell脚本,创建变量时找不到命令

Joh*_*n B 3 shell

我有以下脚本有效:

x=10
echo $x
now=$(date +'%Y-%m-%d')
echo $now
Run Code Online (Sandbox Code Playgroud)

但是,当我在开头添加注释行时:

# comment
x=10
echo $x
now=$(date +'%Y-%m-%d')
echo $now
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

x=10: command not found
x: undefined variable
Run Code Online (Sandbox Code Playgroud)

为什么添加导致脚本失败的注释?

如果我做以下工作它是有效的:

x=10
echo $x
now=$(date +'%Y-%m-%d')
# comment here
echo $now
Run Code Online (Sandbox Code Playgroud)

Wil*_*ell 6

这是csh的怪癖.(停止使用csh!)csh将使用"标准shell"(引自csh联机帮助页)处理不以"#"开头的脚本.当脚本以"#"开头时,csh会对其进行解析.您的脚本无效csh.

你应该添加一个shebang线来避免这种类型的问题.也就是说,制作第一行:

#!/bin/sh