Thursday, April 14, 2016

Shell Programmimg

Overview:

A shell program combines Linux commands in such a way as to perform a specific task. The Linux shell provides you with many programming tools with which to create shell programs. You can define variables and assign values to them. You can also define variables in a script file and have a user interactively enter values for them when the script is executed.

What is Shell:


The shell provides you with an interface to the UNIX system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program's output.

A shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of shells, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized commands and functions.

Shell Prompt:

The prompt, $, which is called command prompt, is issued by the shell. While the prompt is displayed, you can type a command.

Shell Types:

In UNIX there are two major types of shells: 
  1. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $ character. 
  2. The C shell. If you are using a C-type shell, the default prompt is the % character. 
There are again various subcategories for Bourne Shell which are listed as follows: 

  • Bourne shell ( sh) 
  • Korn shell ( ksh) 
  • Bourne Again shell ( bash)
  • POSIX shell ( sh)
The different C-type shells follow: 
  • C shell ( csh) 
  • TENEX/TOPS C shell ( tcsh)
  1. The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he was at AT&T Bell Labs in New Jersey. 
  2. The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as "the shell". 
  3. The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this reason, it is the shell of choice for writing scripts to use on several different versions of UNIX.

Shell Scripts:

The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by a pound sign, #, describing the steps.

We are going to write a many scripts in the next several tutorials. This would be a simple text file in which we would put our all the commands and several other required constructs that tell the shell environment what to do and when to do it. 

Example Script:

Assume we create a test.sh script. Note all the scripts would have .sh extension. Before you add anything else to your script, you need to alert the system that a shell script is being started. This is done using the shebang construct.
For example:-

#!/bin/sh

This tells the system that the commands that follow are to be executed by the Bourne shell. It's called a shebang because the # symbol is called a hash, and the ! symbol is called a bang. To create a script containing these commands, you put the shebang line first and then add the commands:

#!/bin/bash
pwd
ls


Shell Comments: 
You can put your comments in your script as follows:

#!/bin/bash
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
pwd
ls


Now you save the above content and make this script executable as follows:
$chmod +x test.sh

Now you have your shell script ready to be executed as follows:
$./test.sh

This would produce following result:

/home/amrood
index.htm unix-basic_utilities.htm unix-directories.htm
test.sh unix-communication.htm unix-environment.htm
Note: To execute your any program available in current directory you would execute using./program_name

Following script use the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT.

#!/bin/sh
# Author : Zara Ali
# Copyright (c) Thehandsonbook.blogspot.in
# Script follows here:
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"

Here is sample run of the script:
$./test.sh
What is your name?
Zara Ali
Hello, Zara Ali
$

Shell Script - Using Variables:

Avariable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.

A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.

The name of a variable can contain only letters ( a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).

By convention, Unix Shell variables would have their names in UPPERCASE. The following examples are valid variable names:

_ALI
TOKEN_A
VAR_1
VAR_2

Following are the examples of invalid variable names:

2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
The reason you cannot use other characters such as !,*, or - is that these characters have a special meaning for the shell.

Defining Variables:

variable_name=variable_value

For example:

NAME="James Bond"

Above example defines the variable NAME and assigns it the value "James Bond". Variables of this type are called scalar variables. A scalar variable can hold only one value at a time. The shell enables you to store any value you want in a variable. For example:

VAR1="James Bond"
VAR2=100

Accessing Values:

To access the value stored in a variable, prefix its name with the dollar sign ( $): For example, following script would access the value of defined variable NAME and would print it on STDOUT:

#!/bin/sh
NAME="James Bond"
echo $NAME
This would produce following value:

James Bond


Variable Types:

When a shell is running, three main types of variables are present: 
  1. Local Variables: A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at command prompt. 
  2. Environment Variables: An environment variable is a variable that is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually a shell script defines only those environment variables that are needed by the programs that it runs. 
  3. Shell Variables: A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.

Special Variables:

$$: Displays PID of the current shell.
$0: Displays Filename of the current script
$#: The number of arguments supplied to a script.
#?: The exit status of the last command executed.
$!: The process number of the last background command.
$*: All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
$$: The process number of the current shell. For shell scripts, this is the process ID under which they are executing
$@: All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.
$n: These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).

Command-Line Arguments:

The command-line arguments $1, $2, $3,...$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9 as the arguments to the command.

Following script uses various special variables related to command line:
#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"

Here is a sample run for the above script:
$./test.sh James Bond
File Name : ./test.sh
First Parameter : James
First Parameter : Bond
Quoted Values: James Bond
Quoted Values: James Bond
Total Number of Parameters : 2

Special Parameters $* and $@:

There are special parameters that allow accessing all of the command-line arguments at once. $* and $@ both will act the same unless they are enclosed in double quotes, "".

We can write the shell script shown below to process an unknown number of command-line arguments with either the $* or $@ special parameters:
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done

There is one sample run for the above script:
$./test.sh James Bond 10 Years Old
Zara
Ali
10
Years
Old

Exit Status: 

The $? variable represents the exit status of the previous command. Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.

Following is the example of successful command:
$./test.sh James Bond
File Name : ./test.sh
First Parameter : James
First Parameter : Bond
Quoted Values: James Bond
Quoted Values: James Bond
Total Number of Parameters : 2
$echo $?
0
$

Unix Basic Operators:-

There are various operators supported by each shell.
  • Arithmetic Operators. 
  • Relational Operators. 
  • Boolean Operators. 
  • String Operators. 
  • File Test Operators.
The Bourne shell didn't originally have any mechanism to perform simple arithmetic but it uses external programs, either awk or the must simpler program expr.
Here is simple example to add two numbers:
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"

Arithmetic Operators:


Operator

Description
Example

+
Addition - Adds values on either side of the operator

`expr $a + $b` will give 30

-
Subtraction - Subtracts right hand operand from left hand operand

`expr $a - $b` will give -10

*
Multiplication - Multiplies values on either side of the operator

`expr $a * $b` will give 200

/
Division - Divides left hand operand by right hand operand

`expr $b / $a` will give 2

%
Modulus - Divides left hand operand by right hand operand and returns remainder

`expr $b % $a` will give 0

=
Assignment - Assign right operand in left operand

a=$b would assign value of b into a

==
Equality - Compares two numbers, if both are same then returns true.

[ $a == $b ] would return false.

!=
Not Equality - Compares two numbers, if both are different then returns true.

[ $a != $b ] would return true.

Example:
Here is an example which uses all the arithmetic operators


#!/bin/sh
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi

Relational Operators:

Operator

Description
Example

     -eq
Checks if the value of two operands are equal or not, if yes then condition becomes true.

[ $a -eq $b ] is not true.

-ne

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

[ $a -ne $b ] is true.

-gt

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

[ $a -gt $b ] is not true.

-lt

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

[ $a -lt $b ] is true.

-ge

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

[ $a -ge $b ] is not true.

-le

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

[ $a -le $b ] is true.


Example:
Here is an example which uses all the relational operators
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b : a is equal to b"
else
echo "$a -eq $b: a is not equal to b"
fi
if [ $a -ne $b ]
then
echo "$a -ne $b: a is not equal to b"
else
echo "$a -ne $b : a is equal to b"
fi
if [ $a -gt $b ]
then
echo "$a -gt $b: a is greater than b"
else
echo "$a -gt $b: a is not greater than b"
fi
if [ $a -lt $b ]
then
echo "$a -lt $b: a is less than b"
else
echo "$a -lt $b: a is not less than b"
fi
if [ $a -ge $b ]
then
echo "$a -ge $b: a is greater or equal to b"
else
echo "$a -ge $b: a is not greater or equal to b"
fi
if [ $a -le $b ]
then
echo "$a -le $b: a is less or equal to b"
else
echo "$a -le $b: a is not less or equal to b"
fi






















No comments:

Post a Comment