Command not found error in Bash variable assignment

こ雲淡風輕ζ 提交于 2019-11-25 21:36:49

问题


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.


回答1:


You cannot have spaces around your '=' sign.

When you write:

STR = "foo"

bash tries to run a command named STR with 2 arguments (the strings '=' and 'foo')

When you write:

STR =foo

bash tries to run a command named STR with 1 argument (the string '=foo')

When you write:

STR= foo

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:

  1. the first command is exactly equivalent to: STR "=" "foo",
  2. the second is the same as STR "=foo",
  3. and the last is equivalent to STR="" foo.

The relevant section of the sh language spec, section 2.9.1 states:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

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 is a variable assignment, while any string that is not a redirection and does not contain = is a command. In STR = "foo", STR is not a variable assignment.




回答2:


Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 



回答3:


In the interactive mode everything looks fine

$ str="Hello World"
$ echo $str
Hello World

Obviously ! as Johannes said, no space around '='. In case there is any space around '=' then in the interactive mode it gives errors as `

No command 'str' found




回答4:


I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.

#!/bin/bash
STR = "Hello World"
echo $STR

Didn't work because of the spaces around the equal sign. If you were to run...

#!/bin/bash
STR="Hello World"
echo $STR

It would work




回答5:


When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.



来源:https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!