poiu2000
poiu2000

Reputation: 980

Why are shell script variables declared without a preceding `$`?

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...?

Upvotes: 0

Views: 321

Answers (3)

paulsm4
paulsm4

Reputation: 121869

It's basically a syntactical convention.

DOS/.bat file syntax works the same way.

1) to create a variable, no metacharacter.

2) to "dereference" the contents of the variable, use the metacharacter.

DOS:
set VAR=123
echo %VAR%

Upvotes: 0

user507077
user507077

Reputation:

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_1 names a variable, the dollar sign is used to invoke expansion. $var is replaced with var's content; ${var:-foo} is replaced with var's content if it is set and with the word foo if 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 if var contains a file name with full path and extension.

In Perl the sigil in front of the variable tells Perl how to interpret the identifier: $var is a scalar, @var an array, %var a hash etc.

In Ruby the sigil in front of the varible tells Ruby its scope: var is a local variable, $var is a global one, @var is an instance variable of an object and @@var is a class variable.

In C++ we don't have sigils in front of variable names.

Etc.

Upvotes: 6

melpomene
melpomene

Reputation: 85887

In the shell, the $ sign is not part of the variable name. It just tells the shell to replace the following word with the contents of the variable with the same name, i.e. $foo means "insert the contents of the variable foo here".

This is not used when assigning to the variable because there you explicitly don't want to insert the old contents; you want to use the variable itself (in some ways this is similar to dereferencing pointers).

Upvotes: 1

Related Questions