Different ways to initialize a variable
Solution 1
You get same effect.
The $()
is recommended since it's more readable and makes it easier to nest one $()
into another $()
.
Update:
The $()
syntax is a POSIX 1003.1 standard (2004 edition). However, on some older UNIX systems (SunOS, HP-UX, etc.) the /bin/sh
does not understand it.
You might need to use backtick "`" instead or use another shell (usually it's ksh) if you need your script to work on such environment.
If you don't know which syntax to use - use $()
. Backtick syntax is deprecated.
Solution 2
see http://mywiki.wooledge.org/BashFAQ/082
also notice that $()
is POSIX so it does work on sh.
Solution 3
There is another way to initialize a variable to a default one if you haven't initialized it yourself.
[jaypal:~/Temp] a="I have initialized var a"
[jaypal:~/Temp] echo ${a:="Default value"}
I have initialized var a
[jaypal:~/Temp] a=
[jaypal:~/Temp] echo ${a:="Default value"}
Default value
Related videos on Youtube
Paul Manta
Updated on June 04, 2022Comments
-
Paul Manta almost 2 years
As far as I've seen there are two ways to initialize a variable with the output of a process. Is there any difference between these two?
ex1=`echo 'hello world'` ex2=$(echo 'hello world')
-
Paul Manta over 12 yearsSo that operator reads the new value of the variable and outputs the old value. :)
-
jaypal singh over 12 yearsIt is generally used when you pass on values to your script as
$1
,$2
and helps your script run even when those values are not explicitly passed. By this you can implicitly set your variables to run on default values if a value hasn't been assigned to them. This saves about 4-5 lines of code where you check if the variable has been assigned or not, something likeif [ -z "$var" ] then; …
-
Michał Šrajer over 12 years@samus: $() is indeed POSIX (1003.2 I think), but it will not work on old UNIXes. Trust me - I use them everyday.
-
Samus_ over 12 yearsbut that's the point, when we talk about portability we mean POSIX because it's the current standard supported by most platforms, if you have specific requirements that go beyond this then it's a particular case.
-
Michał Šrajer over 12 years@samus: By "more portable" I mean "works on more OSes" not "is compatible with newer POSIX standard".
-
Indrajeet over 10 yearsI believe, we can either use, echo ${a:="Default value"} or echo ${a:-"Default value"}