Pages

Scripting -3 Variables

Aim: Introduction to the usage of variables in shell scripting.

 The concept of variables is common in the programming world. A variable is basically used to hold or store a value, which can change dynamically while the program or the script is running.
The value that is stored in the variable can later be used any where in the script or program by referring the variable.
The syntax of assigning a value to a variable in bash scripting is as follows.

Variable_Name=Value


There should not be any space between the variable name and "=" and also no space between "=" and value.

The value on the left is the name of the variable which has to follow the following rules.
1. It must start with a letter or an Under score.
2. Subsequent characters(After the first one) can be letters,numbers or underscore.
3. Spaces can NOT be used in variable names

Eg :
Valid Variable names : num1, _num1, n1n1.
Invalid  Variable names: 1num, num 1.

The variables are case sensitive, i.e. num1 is not same as NUM1.


In bash scripting to use a variable, once a value is assigned to it, we need the append the name of the variable with a "$" symbol i.e. $variable_name.

Echo can also be used to print the value of a variable

Let't try writing a script using a variable.

#!/bin/sh
var1=10
echo "The value of the variable is"
echo $var1


Type the above lines into a file and save it under the name script3.sh
Use chmod to give execute permission to it.

$ ./script3.sh 
output:
The value of the variable is 
10


The value "10" was saved in the variable "var1", which was later accessed by the echo command by perpending a "$" before the name i.e. $var1. 




A variable can hold any values i.e not only numbers you can assign words, sentences etc to a variable. 


For eg: 


#! /bin/bash
var1="harry" 
echo "His name is $var1"


Write the above script into a file and save it as script4.sh
Run the script after giving execute permission to it.

$ ./script4.sh
Output:
His name is harry


From the above example we see that the variable can be used along with any text of the echo command, only thing we need to make sure is that the name is perpended with a "$" and the whole sentence is inside double quotes.

A script can also be assigned sentences as shown in the example below.

#!/bin/bash 
var1="His name is harry"
echo $var1


Write the above script into a file and save it as script5.sh
Run the script after giving execute permission to it.

$ ./script5.sh 
Output:
His name is harry


Now try this script


#!/bin/bash 
var1=His name is harry
echo $var1


Save the above script as script6.sh.
What do you expect the output to be?

$./script6.sh 
Output:
script6.sh: 2: name: not found


Can you guess why is this ?

The assignment to variable does not take spaces if you remove the double quotes. So "var1" gets assigned "His".  The script then treats the string next to his i.e. "name" as a command, but there is no command called as "name", hence we get the error.

You can also assign commands to variables as shown in the script below.

#!/bin/bash 
list=ls
$list


Save the above script as script7.sh. On executing the script you should see the same output as you would if you executed the command "ls" in your current directory.
The variable "list" get assigned with the value "ls". When the variable by it self is used in the next line, its same as using a command. With the $ perpended before "list"  $list becomes "ls", which in turn gets executed as usual.

You can also club multiple commands into one variable as shown in the script below.

#!/bin/bash
store="ls > file"
$store

Save the above script as script8.sh, guess what would be the output.

De-assigning a Variable


In case you want to remove the value the you have assigned to a variable, you can use the command "unset"

syntax:
$ unset variable_name


For eg:
$ var1=10
$ echo $var1
10
$ unset $var1
$ echo $var1


$

In the above sequence of commands, we first assign the value of 10 to the variable "var1", which we display using the command "echo".
Then using the "unset" command on the variable "var1",  it gets de-assigned.
After the "unset" we try using he "echo" command again on "var1" but it does not display any value thus proving that the value has been de-assigned.


Taking Input from the user 


Until now we have seen scripts that set the value of the variable in the script it self. But a variable's real use is when we can allow it to be modified by the user.
In a number of situations we would need the user to provide us with certain data with which we need to work in the script. For situations like this, when we need to take the input from the user, we can use the command "read".

syntax:
read variable_name


The read commands basically waits for the user to enter a value, which in turn gets assigned to the "variable" passed to the read command.
For eg:

#!/bin/bash
echo "What is your name?"
read name
echo "My name is $name"

Save the above script as script8.sh and execute it.

$ ./script8.sh 
Output:
what is your name 
( The script waits here with a blinking cursor, as long as you don't  enter a value. The value entered in turn gets assigned to "name" )
Harry (Assume we entered this)
My name is Harry

Note:  "echo" by default inserts a new line at the end, in case you don't want the new line and want to continue in the same line use the option     "-n" with echo, i.e. "echo -n"




More scripts 


Write a script that will ask the user for a filename, and output the content of the file.
Note: Assume that the user enters a file that exists in the current directory, we will see how we can do a check whether the file is existing or not a little later. 


#!/bin/bash
echo "Enter the filename" 
read file
cat $file


Save it as script9.sh, and run it to check whether you get the desired output.


Write a script that will take the name,phone number and email-id of a user one by one and later display it all together.

#!/bin/bash 
echo -n "Hello, enter your name: " 
read name
echo -n "Enter your phone number :" 
read number 
echo -n  "Enter your email id: " 
read email 
echo "Thank you $name, your phone number is $number and your email is
           $email"



Save the script as script10.sh, and run it.

Output:

$ ./script10.sh 
Hello, enter your name: Harry
Enter your phone number : 9999
Enter your email id: abc@abc.com

Thank you Harry, your phone number is 9999 and your email is abc@abc.com

Notice that in the above script we have used the "-n" option with echo, thus the input prompt stays on the same line after the echo. 
Also notice that there are not limits on how many times you can use the read command in a script, neither is there are limit of where you can use the command.

Ways to reference Variables : 

There are three ways you can reference a variable and access its value.
If var1 is the name of the variable

1. $var1
2. ${var1}
3. {$var1}

In all the three methods we will get the value stored in the variable.

For eg:

#!/bin/bash 
var1=10
echo $var1
echo {$var1}
echo ${var1} 

output:
10
{10}
10

Quotes:


While scripting you will come across three kinds of quotes.Each of these quotes have their own meaning.

1. " "The double quote
       With in double quotes every special character holds its special meaning.
        For eg:
        "$" is used to before a variable to print its value, with in double quotes the "$"  
         will still function the same.
          For Eg:
          #!/bin/bash
           var1=10
          echo "Value is $var1" 
           
          Output
          10


2. ' Single quote
      Any special symbol placed between the single quotes looses its special meaning.
          #!/bin/bash
           var1=10
          echo "Value is $var1" 
           
          Output 
          $var1

3. ` Backtick
     A backtick is also called as the command substitution. Only a command or a script can be  placed between the backticks. The script or the command gets executed and the value gets replaced at the place.
      For eg:

#!/bin/bash

          echo `cat file1` 
           
          Output 
          "contents of file1"

In the above script we placed the command "cat file1" between the backticks, thus instead of printing the string "cat file1" the command "cat file1" got executed, whose contents in turn were passed to echo, thus echo put out the contents of file1 on to the screen. 







No comments:

Post a Comment