Unix Shell Programming
What is Shell ?
• Unix Shells are the executables that provide the user-
interface to the user.
• Shell as a Command Interpreter.
• The shell is an intermediary program, which interprets the
command that are typed at the terminal, and translates
them into commands that are understood by the kernel.
• Shells also provides:
Command Interpretation,
I/O Re-Direction ,Pipes
Command History ,
Variables & Programming Constructs ,Job Control
Shell Scripts
shells are interactive. It means shell accept command
from you (via keyboard) and execute them. But if you
use command one by one (sequence of 'n' number of
commands) , the you can store this sequence of
command to text file and tell the shell to execute this
text file instead of entering the commands. This is
know as shell script.
Shell script defined as:
"Shell Script is series of command written in plain text
file. Shell script is just like batch file is MS-DOS
but have more power than the MS-DOS batch file."
Why to Write Shell Script ?
script can take input from user, file and
output them on screen.
• Useful to create our own commands.
• Save lots of time.
• To automate some task of day today life.
• System Administration part can be also
automated.
Types Unix Shells
• Bourne Shell
• Korn Shell
• C Shell
• Bourne Again Shell
Bourne Shell
• The Bourne shell is the original UNIX shell program
• It is very widely used
• Invoked using sh or /bin/sh at the command prompt
• The Bourne shell supports conditional branching in the
form of if/then/else statements
• In addition, the Bourne shell supports case statements
and loops (for, while, and until)
• The Bourne shell uses the $ as a prompt
Korn shell
•The Korn shell is a newer variation of the Bourne shell.
• It supports everything the Bourne shell does, and adds
features not available in the Bourne shell.
• Invoked using ksh or /bin/ksh at the command shell
prompt.
• The Korn shell was originally written by David Korn and
is copyrighted by AT&T.
• The programming structure of the Korn shell is very
similar to that of the Bourne shell. The Korn shell,
however, is more interactive.
C Shell
• The C shell is a very commonly used shell.
• Its programming structure closely resembles that of the
programming language "C."
• The C shell uses the "%" as a prompt.
• The C shell supports all of the features that the Bourne
shell supports, and has a more natural syntax for
programming .
• The C shell is more interactive than the Bourne shell, with
additional features that are not available in older shells.
• The configuration of the C shell is controlled by the .rc and
the .login files.
Bourne-Again Shell
• The Bourne-Again shell is a variation of the Bourne shell
• It is commonly used in Linux, but is widely available in
other standard UNIX distributions
• The Bourne Again shell is another modification of the
Bourne shell, and uses the $ as a prompt
• To start the Bourne Again shell, type "bash" at the shell
prompt
• The behavior and environment of the Bourne Again shell
is controlled by the .bashrc file, which is a hidden file in
your home directory
Types of Shell – Comparison
Shell Type
Feature sh csh ksh bash
Job Control O P P P
Command History O P P P
Command Line Editing O O P P
Local Variables O O P P
Aliases O P P P
Custom Prompt O O P P
How to write shell script
Following steps are required to write shell
script:
(1) Use any editor like vi to write shell script.
(2) After writing shell script set execute
permission for your script as follows.
(3) Execute your script as.
Perform all steps:
1)Write shell script
$ vi first
# My first shell script
clear
echo "Knowledge is Power"
Assign permission to shell script
(2) After writing shell script set execute
permission for your script as follows
syntax:
chmod permission your-script-name
Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name
Execute shell script
(3) Execute your script as
syntax:
bash your-script-name
sh your-script-name
./your-script-name
Examples:
$ bash bar
$ sh bar
$ ./bar
Shell Variables
User-created Shell Variables:
variable=value => assigns value to variable
$variable => refers value of the variable
To display a variable:
echo $var “$var” ‘$var’
the output:
hello hello $var
read statement:
To read a value in a variable form keyboard:
read var
Unix - Special Variables
Variable Description
$# The number of positional parameters.
$- Shell Options.
$? The exit status of the last executed command.
$$ The process number (PID) of the last executed
command.
$! The process number (PID) of the last background
command.
$0 The name of the command being executed.
$* List of positional parameters.
$@ Same as $* except when enclosed in double quotes
Shell Arithmetic Operators
expr command
This command is used to evaluates expressions. Use
to perform arithmetic operations.
Syntax:
expr op1 math-operator op2
e.g.
expr 10 + 20
Operators
Arithmetic:
+ Add
- Subtract
/ Divide
\* Multiply
% Modulo
Command Line Arguments
The most important concept in shell scripts is passing
arguments to a script.
•The number after the dollar sign indicates the position on
the command line.
•That is, "$1" indicates the first parameter, and "$2"
indicates the second.
•Positional Parameters are $1, $2, ..., $9
•$0 - Script name
Relational Operator
Operator Description
> (-gt) Greater than
< (-lt) Less than
> = (-ge) Greater than or equal
<= (-le) Less than or equal
== (-eq) Equal to (comparison)
!= (-ne) Not equal to
&& (-a) And
|| (-o) Or
Conditional Statement: if-then-else
The if statement takes two-way decisions depending on the
condition.
if condition if condition if condition
then then then
commands commands commands
fi else elif condition
then
commands commands
fi else
commands
fi
Case Statement
The statement matches an expression for more
than one alternative, and permits multi-way
branching
case variable/expression/value in
value1) command1
command2
;;
value2) command3
;;
*) command4
esac
Loops
• Loop statements
• Involve repeating portion of the program
while loop
Executes a list of statements repeatedly
while a certain condition holds true.
Syntax:
while condition
do
command(s)
done
For loop
for loop
Executes a list of statements a fixed number of
times.
Syntax
for variable in v1 v2 v3 v4
do
Will work for list of values mentioned here
command(s)
done
Variable declaration not required
Until loop
until loop
Executes a list of statements repeatedly till
condition remains false
Syntax
until condition
do
command(s)
done
Adv Shell Scripting
String Operations
String Description
Operation
= True if strings are same
!= True if strings are different
-n True if length of string is greater than 0
-z True if the length of string is zero
< True if string one is less than the two
> True if string two is less than the one
File Checking Attributes
Variable Description
-d True if directory exists
-f True if file exists
-r True if read permission
-w True if write permission
-x True if executes permission
-s file True if size is greater than 0 and exist
Test Operators
There are following operators to test various properties
associated with a Unix file .
Example:
# !/bin/ksh
num1=10
num2=30
num3="demo1.sh“
# compare greater than
test $num1 -gt $num2
echo $?
# check file
test -f $num3
echo $?
Command substitution
Command substitution is the mechanism by which the
shell performs a given set of commands and then
substitutes their output in the place of the commands.
Syntax
`command`
When performing command substitution make sure that
you are using the backquote, not the single quote
character.
Example
Echo “Today is `date` “
Array
•Shell supports a different type of variable called an array
variable that can hold multiple values at the same time.
Arrays provide a method of grouping a set of variables.
•Defining Array as follows −
array_name[index]=value
• Accessing Array Values
After you have set any array variable, you access it as follows
${array_name[index]}
Array Contd
• You can access all the items in an array in one of the
following ways −
${array_name[*]}
${array_name[@]}
Functions
• Functions enable you to break down the overall
functionality of a script into smaller, logical subsections,
which can then be called upon to perform their individual
task when it is needed.
• Using functions to perform repetitive tasks is an excellent
way to create code reuse. Code reuse is an important part
of modern object-oriented programming principles.
• Shell functions are similar to subroutines, procedures,
and functions in other programming languages.
Creating Functions
To declare a function, simply use the following
syntax −
function_name () { list of commands }
Example
#!/bin/sh
# Define your function here
Hello()
{
echo "Hello!!!!"
}
# Invoke your function
Hello
Pass Parameters to a Function
You can define a function which would accept
parameters while calling those function. These
parameters would be represented by $1, $2 and so on.
Returning Values from Functions
• If you execute an exit command from inside a function,
its effect is not only to terminate execution of the function
but also of the shell program that called the function.
• Based on the situation you can return any value from
your function using the return command