Bash 变量赋值中出现命令未找到错误
我有一个名为 test.sh 的脚本:
#!/bin/bash
STR = "Hello World"
echo $STR
当我运行 sh test.sh
时,我得到以下信息:
test.sh: line 2: STR: command not found
我做错了什么?我在网上查看非常基本/初学者的 bash 脚本教程,这就是他们所说的声明变量的方式......所以我不确定我做错了什么。
我使用的是 Ubuntu Server 9.10。是的,bash 位于 /bin/bash
。
I have this script called test.sh:
#!/bin/bash
STR = "Hello World"
echo $STR
when I run sh test.sh
I get this:
test.sh: line 2: STR: command not found
What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.
I'm on Ubuntu Server 9.10. And yes, bash is located at /bin/bash
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
=
符号周围不能有空格。当您编写时:
bash 尝试运行一个名为
STR
的命令,该命令带有 2 个参数(字符串=
和foo
)当您编写时:
bash 尝试运行运行名为
STR
并带有 1 个参数(字符串=foo
)的命令当您编写:
bash 尝试运行命令
foo
,并将 STR 设置为其环境中的空字符串。我不确定这是否有助于澄清或仅仅是混淆,但请注意:
STR "=" "foo"
,STR "=foo"
,STR="" foo
。sh 语言规范第 2.9.1 节的相关部分状态:
在这种情况下,一个单词就是 bash 将要运行的命令。任何包含
=
的字符串(在字符串开头以外的任何位置),该字符串不是重定向,并且其中=
之前的字符串部分是有效的变量名是变量赋值,而任何不是重定向或变量赋值的字符串都是命令。在STR = "foo"
中,STR
不是变量赋值。You cannot have spaces around the
=
sign.When you write:
bash tries to run a command named
STR
with 2 arguments (the strings=
andfoo
)When you write:
bash tries to run a command named
STR
with 1 argument (the string=foo
)When you write:
bash tries to run the command
foo
with STR set to the empty string in its environment.I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
In that context, a
word
is the command that bash is going to run. Any string containing=
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the=
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. InSTR = "foo"
,STR
is not a variable assignment.删除
=
符号周围的空格:Drop the spaces around the
=
sign:在交互模式下,一切看起来都很好:
显然(!)正如 Johannes 所说,
=
周围没有空格。如果=
周围有任何空格,那么在交互模式下它会给出错误:In the interactive mode everything looks fine:
Obviously(!) as Johannes said, no space around
=
. In case there is any space around=
then in the interactive mode it gives errors as我知道这个问题已经得到了非常高质量的回答。但是,简而言之,不能有空格。
由于等号周围有空格,所以不起作用。如果你要跑...
它会起作用
I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.
Didn't work because of the spaces around the equal sign. If you were to run...
It would work
当您定义任何变量时,您不必输入任何额外的空格。
例如
,删除空格:
它会正常工作。
When you define any variable then you do not have to put in any extra spaces.
E.g.
So remove spaces:
and it will work fine.
要添加到接受的答案 - 在变量名称中使用破折号将给出相同的错误。删除
-
以消除错误。To add to the accepted answer - using dashes in your variable name will give the same error. Remove
-
to get rid of the error.