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.
You cannot have spaces around the
=sign.When you write:
bash tries to run a command named
STRwith 2 arguments (the strings=andfoo)When you write:
bash tries to run a command named
STRwith 1 argument (the string=foo)When you write:
bash tries to run the command
foowith 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
wordis 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",STRis not a variable assignment.