PDA

View Full Version : [ubuntu] shell variable declaration



vksingh
March 6th, 2010, 04:12 PM
Hi,

What is the difference between the following shell assignments:

$x="vivek"

$x=vivek

Please help.

Thanks,

Vivek

asmoore82
March 6th, 2010, 08:43 PM
For BASH, you don't use the dollar sign($) when declaring variables, only when referencing them.

It's good practice to always enclose the variable value in quotation marks
and always enclose variable references in quotation marks...


#sloppy work, no quotes
$ greeting=hello
$ echo $greeting
hello
#will lead to errors
$ greeting=Hello World
World: command not found

#much better scripting
$ greeting="Hello World"
$ echo "$greeting"
Hello World

#declaring an array
$ conversation=( "$greeting" "How are you?" "Goodnight, ladies." )

#more sloppy work, no quotes leads to bad behavior
$ for message in ${conversation[@]}
> do
> echo $message
> done
Hello
World
How
are
you?
Goodnight,
ladies.

#much better scripting
$ for message in "${conversation[@]}"
> do
> echo "$message"
> done
Hello World
How are you?
Goodnight, ladies.