Thursday, April 14, 2016

Shell Scripts Examples

Examples:
#!/bin/sh
# This is some secure program that uses security.

VALID_PASSWORD="secret" #this is our password.

echo "Please enter the password:"
read PASSWORD

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
        echo "You have access!"
else
        echo "ACCESS DENIED!"
fi

#!/bin/sh
 
# Prompt for a user name...
echo "Please enter your age:"
read AGE
 
if [ "$AGE" -lt 20 ] || [ "$AGE" -ge 50 ]; then
        echo "Sorry, you are out of the age range."
elif [ "$AGE" -ge 20 ] && [ "$AGE" -lt 30 ]; then
        echo "You are in your 20s"
elif [ "$AGE" -ge 30 ] && [ "$AGE" -lt 40 ]; then
        echo "You are in your 30s"
elif [ "$AGE" -ge 40 ] && [ "$AGE" -lt 50 ]; then
        echo "You are in your 40s"
fi

#!/bin/sh

a=10

b=20

if [ $a == $b ]

then

   echo "a is equal to b"

else

   echo "a is not equal to b"

fi
Until Loop:
The while loop is perfect for a situation where you need to execute a set of commands while some condition is true. Sometimes you need to execute a set of commands until a condition is true.
#!/bin/sh

a=10

until [ $a -ge 10 ]

do

   echo $a

   a=`expr $a + 1`

done
__________________________________________________
#!/bin/sh

a=0

until [ ! $a -lt 10 ]

do

   echo $a

   a=`expr $a + 1`

done

Break command: -The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement
#!/bin/sh

a=0

while [ $a -lt 10 ]

do

   echo $a

   if [ $a -eq 5 ]

   then

      break

   fi

   a=`expr $a + 1`

done

Examples for FOR Loop:
1. Static values for the list after “in” keyword
$ cat for1.sh
i=1
for day in Mon Tue Wed Thu Fri
do
 echo "Weekday $((i++)) : $day"
done
$ cat for1-wrong1.sh
i=1
for day in Mon, Tue, Wed, Thu, Fri
do
 echo "Weekday $((i++)) : $day"
done
$ cat for1-wrong2.sh
i=1
for day in "Mon Tue Wed Thu Fri"
do
 echo "Weekday $((i++)) : $day"
done
$ cat for2.sh
i=1
weekdays="Mon Tue Wed Thu Fri"
for day in $weekdays
do
 echo "Weekday $((i++)) : $day"
done
$ cat for2-wrong.sh
i=1
weekdays="Mon Tue Wed Thu Fri"
for day in "$weekdays"
do
 echo "Weekday $((i++)) : $day"
done
$ cat for3.sh
i=1
for day
do
 echo "Weekday $((i++)) : $day"
done


O/P: - $ ./for3.sh Mon Tue Wed Thu Fri
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri
$ cat for4.sh
i=1
for day in
do
 echo "Weekday $((i++)) : $day"
done


O/P: - $ ./for3.sh Mon Tue Wed Thu Fri
Will get no output for above script.


$ cat for5.sh
i=1
cd ~
for item in *
do
 echo "Item $((i++)) : $item"
done

$ cat for5-1.sh
i=1
for file in /etc/[abcd]*.conf
do
 echo "File $((i++)) : $file"
done

$ cat for6.sh
i=1
for day in Mon Tue Wed Thu Fri
do
 echo "Weekday $((i++)) : $day"
 if [ $i -eq 3 ]; then
   break;
 fi
done

Example for Continue:
$ cat for7.sh
i=1
for day in Mon Tue Wed Thu Fri Sat Sun
do
 echo -n "Day $((i++)) : $day"
 if [ $i -eq 7 -o $i -eq 8 ]; then
   echo " (WEEKEND)"
   continue;
 fi
 echo " (weekday)"
done

$ cat for8.sh
for (( i=1; i <= 5; i++ ))
do
 echo "Random number $i: $RANDOM"
done
Infinite Bash loop script

$ cat for9.sh
i=1;
for (( ; ; ))
do
   sleep $i
   echo "Number: $((i++))"
done

Range of numbers after “in” keyword

$ cat for11.sh
for num in {1..10}
do
 echo "Number: $num"
done

Range of numbers with increments after “in” keyword

$ cat for12.sh
for num in {1..10..2}
do
 echo "Number: $num"
done

Unix -- Class:1

UNIX Introduction

What is Unix ?
The UNIX operating system is a set of programs that act as a link between the computer and the user

Unix History

  • Unix was originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.
  • There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are few examples. Linux is also a flavor of Unix which is freely available
  • Several people can use a UNIX computer at the same time; hence UNIX is called a multiuser system
  • A user can also run multiple programs at the same time; hence UNIX is called multitasking.

Users communicate with the kernel through a program known as the shell. The shell is a command line interpreter; it translates commands entered by the user and converts them into a language that is understood by the kernel.

Unix Architecture:



Kernel: The kernel is the heart of the operating system. It interacts with hardware and most of the tasks like memory management, tash scheduling and file management.

Shell: The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI).

Commands and Utilities: There are various command and utilities which you would use in your day to day activities. cp, mv, cat and grep etc. are few examples of commands and utilities. There are over 250 standard commands plus numerous others provided through 3rd party software. All the commands come along with various optional options.

Files and Directories: All data in UNIX is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the filesystem.

In the diagram above, we see that the directory ee51ab contains the subdirectory unixstuff and a file proj.txt

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