[Solved-3 Solutions] Command not found error in Bash variable assignment
Error Description:
In a script:
#!/bin/bash
STR = "Hello World"
echo $STR
click below button to copy the code. By Bash tutorial team
- when we run sh test.sh we get this:
test.sh: line 2: STR: command not found
click below button to copy the code. By Bash tutorial team
Solution 1:
- You cannot have spaces around your '=' sign.
- When you write:
STR = "foo"
click below button to copy the code. By Bash tutorial team
- 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 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. 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.
- 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.
Solution 2:
#!/bin/bash
STR="Hello World"
echo $STR
click below button to copy the code. By Bash tutorial team
Solution 3:
- When you define any variable then you do not have to put in any extra spaces.
E.g.
name = "Wikitechy"
// it is not valid, you will get an error saying- "Command not found"
click below button to copy the code. By Bash tutorial team
- So remove spaces:
name=" Wikitechy "