Understanding Variables in Shell Scripting



A number of beautiful and powerful programming languages, like Python, Ruby, and Perl are available for scripting needs. Even then you may find the old school unix shell scripting very useful tool to learn and use. For sure, shell scripts looks crazy and hard to read/understand. Once you get a hang of it, you might find it extremely useful.

From the beginners’ perspective, one aspect of shell scripting that might drive one nuts is defining and using variables in a shell script. Here is the basics of understanding variables in shell scripting.

Defining a Variable in Shell Scripting

Just like any programming language, a variable is name for holding some value. Typically, shell variables hold string values. Variables in a shell script can begin with a letter or underscore and can contain letters/numbers/underscores. Here is example of defining a variable.

my_var=it_is_a_string

An important thing to note in defining a variable, there is no empty space between “=” sign and the variable name and value. And you may also have noticed that there is no “double quotes” in defining the string variable. The rule in shell scripting is that double quotes are not needed when there is no empty space in the variable. And you do need double quotes, if the value of your variable has empty space in it, like

my_var=”it is a string”.

How to Use a Variable in Shell Scripting?

IN shell scripting the variable name can not be simply used to get the value of variable.
To use the variable, one need to use “$” sign in front of the variable name, like

echo $my_var

will print the value of “my_var” on the terminal. (The use of the variable like “echo my_var” will result in error”.)

Just like other languages, one variable can be assigned to another variable, like

my_new_var = $my_var

. However, if one uses more than one variable in defining a new variable, they have to be with a double quote. For example, we have two variables

last_name=Smith
first_name=John

and we want to create a new variable “full_name” using the above two variables, then

full_name = “$first_name $last_name”.