views:

668

answers:

4

This seems like such a simple question I'm embarrassed to ask it:

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.

UPDATED: Ya... I knew it was something simple like that. Thanks

+3  A: 

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 
Joey
This is funny, though, as `set foo = bar` is a common mistake in Windows batch files as well—and there the batch language is ridiculed for it ;-)
Joey
wow.. that can drive a newbie nutz... thanks+1
AlexanderN
+4  A: 

You cannot have spaces around your '=' sign.

William Pursell
+1  A: 

It's also a good idea to use curly braces around your variables when referencing them.

So:

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

becomes:

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

It is a more explicit way to reference your variables later. It is necessary if you print a variable with text. Here's a simplified example:

#!/bin/bash 
# list all the report files for January in a directory
REP_MONTH=January
ls ./$REP_MONTH.rpt

The code above will give an error as there is no variable $REP_MONTH.rpt. However, if you use the full syntax (curly braces) with your variable, your intent is clearer and can be interpreted without error.

#!/bin/bash 
# list all the report files for January in a directory
REP_MONTH=January
ls ./${REP_MONTH}.rpt

The curly braces clearly identify the bash variable in the command construct.

Jim
A: 

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

Arkapravo