Wednesday, October 26, 2011

Shell Variables

Working with Shell variables.

As like any other programming languages shell also has variable (most people dont know we can do programming with shell commands.). The shell variables takes single values as strings, even the numeric values is also considered as string.

Declaring and assigning shell variable:
You can declare and assign shell variable as simple as below.
bash-3.00$ color=yellow

You need to be careful while doing this. There should not be any space before and after equal to sign '=', if exists throws error.


Referencing a shell variable:
Below command will display the value stored in the variable color


bash-3.00$ echo $color
yellow


 

what is the output?
bash-3.00$ echo $coloryish

As no variable is declared as coloryish the output will be null. If you are actually interested to display "yellowyish", place the variable in curly braces as below.

bash-3.00$ echo ${color}yish
yellowyish


What if instead of variable color we supplied colour, which is not defined?
bash-3.00$ echo The dress is ${colour}ish
The dress is ish

How to handle this? Fortunately shell helps us to have default values to be set in case the variable is not defined as below
bash-3.00$ echo The dress is ${colour:-green}ish
The dress is greenish


The default value will come into effect only if the variable referenced  is not declared. The syntax :- tells the shell to print the following character

Assigning Variables with read command:
We can assign values to multiple variables at a time with read commnad.

bash-3.00$ read city state message
Thazhekode Kerala Hi Mom!

The above command declares three variables city, state and message and assign values respectively.
city=Thazhekode
state=Kerala
message=Hi Mom!

bash-3.00$ read city state message
Thazhekode New Jersey Hi Mom!

city=Thazhekode
state=New
message=Jersy Hi Mom!

Read command assigns an individual word to a specified variable, and the remaining words are assigned to the last variable. To handle this situation you can use the escape character

bash-3.00$ read city state message
Thazhekode New\ Jersey Hi Mom!




No comments:

Post a Comment