tags:

views:

69

answers:

4

I found these two:

[root@~]# echo $i;
2
[root@~]# echo ${i};
2
A: 
echo ${!var}

echo ${array[$i]}

set -- $var; echo $1 $2
ghostdog74
A: 

Actually both of those are the SAME way.

the difference is that one is very specific in what variable you want, and the other is a bit general. for example, if you wanted to print "2cents" (note the lack of a space), then extending your examples would look like this:

echo $icents;

which would fail because you don't have a variable "icents", but the other example:

echo ${i}cents;

would properly print out "2cents" because the dereference "$" is applied to the explicit variable "i" with the curly braces acting as indicators where the variable name starts and stops.

It takes extra typing, but most of the time it is much, MUCH better to always include the curly braces around a variable name.

Edwin Buck
I think the "always use curly braces" is a bit of a style call - there are so many cases in which it's very clear they're not needed. If you insist on having a rule like that, a less frustrating one is "always use curly braces if there's anything besides whitespace or quotes after the variable name"
Jefromi
Agreed. It is very much a style call, except that it is one of those style calls which actually can prevent a large number of bugs from creeping into your program. So as far as style calls go, it's a bit better than arguing about indentation or what should go on a new line.
Edwin Buck
+1  A: 

Here is some information in addition to answers by others.

Scalar variables may be reference using array syntax:

name="dennis williamson"    # scalar
# These all work the same when there's only one element
echo ${name[@]}
echo ${name[*]}
echo ${name[0]}

You can display a variable's contents and other information about it in a variety of ways:

echo "$var"
printf "$var\n"
declare -p var

List all the variable names that start with a given prefix:

echo ${!va*}
echo ${!va@}

The * and @ here and above affect whether the result is expanded to separate words when double quoted.

$ array=(red green blue)
$ for color in "${array[@]}"; do echo $color; done
red
green
blue
$ for color in "${array[*]}"; do echo $color; done
red green blue

Without the double quotes they would both print the colors on separate lines as in the version with @.

If the variable is exported into the environment, you can do one of these:

export | grep var
declare -x | grep var
set | grep var
env | grep var

You can print a list of all the local variables within a function:

local

Also, see this SO question regarding arithmetic expressions and the documentation regarding shell parameters and parameter expansion.

Dennis Williamson
A: 

As others have already started describing, there a several different ways to get a variables value in bash. For simple variables, when all you want is the full, unmodified value, obtained in the safest way possible, use the "${i}" syntax.

Kevin Little