I noticed that in shell script when we declare a variable, the preceding dollar sign is not needed, although when we want to access this variable later we should add a dollar sign in front of this variable name.
just like:
#!/bin/sh
VAR_1=Hello
VAR_2=Unix
echo "$VAR_1 $VAR_2"
This is different from other languages, like Perl we will always have the preceding dollar sign with the variable name, I just want to know any good reason for shell script to do it in this way, or it’s just a convention…?
Shell is a different language than Perl is a different language than C++ is a different language than Python. You can add “with different rules” to each of the languages.
In shell an identifier like
VAR_1names a variable, the dollar sign is used to invoke expansion.$varis replaced withvar‘s content;${var:-foo}is replaced withvar‘s content if it is set and with the wordfooif the variable isn’t set. Expansion works on non-variables as well, e.g. you can chain expansion like${${var##*/}%.*}should leave only a file base name ifvarcontains a file name with full path and extension.In Perl the sigil in front of the variable tells Perl how to interpret the identifier:
$varis a scalar,@varan array,%vara hash etc.In Ruby the sigil in front of the varible tells Ruby its scope:
varis a local variable,$varis a global one,@varis an instance variable of an object and@@varis a class variable.In C++ we don’t have sigils in front of variable names.
Etc.