Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command not found error in Bash variable assignment

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.

like image 465
Jake Wilson Avatar asked Feb 15 '10 18:02

Jake Wilson


People also ask

How do I fix bash command not found?

Sometimes when you try to use a command and Bash displays the "Command not found" error, it might be because the program is not installed on your system. Correct this by installing a software package containing the command.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@

What does $() mean bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


2 Answers

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:

  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 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.

like image 107
William Pursell Avatar answered Oct 02 '22 20:10

William Pursell


Drop the spaces around the = sign:

#!/bin/bash  STR="Hello World"  echo $STR  
like image 37
Joey Avatar answered Oct 02 '22 22:10

Joey