Command not found error in Bash variable assignment
Drop the spaces around the =
sign:
#!/bin/bash
STR="Hello World"
echo $STR
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
You cannot have spaces around the =
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:
- the first command is exactly equivalent to:
STR "=" "foo"
, - the second is the same as
STR "=foo"
, - 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 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. In STR = "foo"
, STR
is not a variable assignment.
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