How many different ways are there to get variable value in bash?
I found these two:
[root@~]# echo $i;
2
[root@~]# echo ${i};
2
开发者_如何学C
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.
echo ${!var}
echo ${array[$i]}
set -- $var; echo $1 $2
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.
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.
精彩评论