0% found this document useful (0 votes)
14 views

Linux Notes Module 3

Module III covers the basics of shell programming, including the definition of a shell, types of shells in Linux, and the use of shell scripts. It discusses shell variables, their types, and rules for naming them, as well as various control structures like if statements and loops. Additionally, it provides syntax and examples for using commands, operators, and control structures in shell scripting.

Uploaded by

padickalhouse123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Linux Notes Module 3

Module III covers the basics of shell programming, including the definition of a shell, types of shells in Linux, and the use of shell scripts. It discusses shell variables, their types, and rules for naming them, as well as various control structures like if statements and loops. Additionally, it provides syntax and examples for using commands, operators, and control structures in shell scripting.

Uploaded by

padickalhouse123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Module III : Shell Programming

Basics of shell programming:


A shell is a command line interpreter. Shell is a user interface that helps a user to interact with the
Linux OS. It allows us to interact with it by entering commands from the keyboard, execute the commands
and display its output on the monitor. The interaction is text – based. This type of interface is called Command
Line Interface or CLI.
To determine the current active shell, use the command: echo $0
To find all available shells in the system, use the command: cat / etc / shells
The shell script is a computer program containing variables, control structures, commands, functions,
etc. it is designed to run by the Linux Shell.
Types of Shell
There are many types of Shells in Linux
1. Bourne Shell (sh) - It is the original UNIX shell. It is portable, compact in size, requires minimal
resources and executes quickly. It is the base of other shells like Korn Shell, Bourne Again Shell and
POSIX shell.
2. BASH Shell (bash) - It is a popular shell, now found as the default on most Linux systems. It is a
freeware shell.
One can start a bash shell session using the bsh command
The executable file name is ‘bsh’.
Its full path name is ‘/bin/bsh’.
The default prompt for non-root user is ‘$’
The default prompt for root user is ‘#’
3. Korn Shell (ksh) - It is compatible with Bourn shell. It includes most of the features of Bourne
Shell. It provides better performance.
The executable file name is ‘ksh’.
Its full path name is ‘/bin/ksh’.
The default prompt for non-root user is ‘$’
The default prompt for root user is ‘#’
4. C Shell (csh) - It uses the syntax of the C programming language. It provides interactive
features such as command alias and history to make it more suitable for interactive applications. But
the script language of the C shell is not compatible with Bourne, Korn and BASH Shells.
The executable file name is ‘csh’.
Its full path name is ‘/bin/csh’.
The default prompt for non-root user is ‘%’
The default prompt for root user is ‘#’
5. Tenex C Shell (tcsh) - It is an extended version of C Shell. It has programmable command line
completion, command line editing, and few other features.
The executable file name is ‘csh’.
6. Z Shell (zsh) - It is an extended Bourne Shell with a large number of improvements. It
includes some features of bash, ksh and tcsh. It has some unique features like file name generation.
ZShell is much more configurable than Bash. ZShell Supports plugins and themes.
7. Restricted shell - It can provide limited access to the operating system. It is useful to the user who only
needs limited rights and permissions. A restricted shell provides an extra layer of security and restricts
certain features of the shell.
8. A shell - It is an extremely small shell, making it fast, but without many advanced features, such as
command line editing or history features, making it difficult to use as an interactive shell. The
executable file name is ‘ash’.
Some other shells are Ashell, Restricted shell, etc.

Shell Name Developed By Where Remark


AT & T Bell labs for
Bourne Shell Stephen Bourne Original UNIX Shell
Unix system in 1977
As part of GNU Most common Shell
BASH Shell Brain Fox
project in 1988 in Linux
AT & T Bell labs in
Korn Shell David G Korn Better performance
1983
Similar to C
University of
C Shell Bill Joy Programming
California
language
Cornegie Millon Enhanced version of
Tenex C Shell Ken Greer
University C Shell
While studying at
Powerful scripting
Z Shell Paul Falstad Princeton University
language
in 1990

Shell Programming

echo command in linux is used to display lines of text or string that are passed as an argument. This is a
built-in command that is mostly used in shell scripts and batch files to output status text to the screen or a
file.
Syntax :
echo [option] [string]
Options Description
-n do not print the trailing newline.
-e enable interpretation of backslash escapes.
\b backspace
\\ backslash
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
Examples:
1. $ echo Welcome //Output : Welcome
2. $ x=10
$ echo The value of variable x = $x //Output :The value of variable x = 10
3. $ echo -e “Welcome \nto \nLinux” //Output : Welcome
to
Linux
Shell Variables
What is a shell environment? (2 marks May 23)
A shell maintains an environment that includes a set of variables defined by the
login program, the system initialization file, and the user initialization files. In
addition, some variables are defined by default.

Explain different types of variables in shell script. (5 marks May 23)


In shell scripting there are three main types of variables present. They are –
Shell variables are variables used in shell programming. Two types are :
1. user defined shell variables
2. system defined shell variables
User defined shell variables are of two types. They are
∙ Local Variables -A local variable is a special type of variable which has its scope
only within a specific function or block of code
∙ Global Variables or Environment Variables-A global variable is a variable with
global scope. It is accessible throughout the program.

System Defined Shell Variables - These variables are pre-defined variables. They are
created and maintained by Linux Shell itself. These variables are required by the shell to
function properly. They are defined in Capital letters. Following are some system defined
shell variables.
1. PATH - Describes the directories that are to be searched whenever a command is
executed. A colon (:) separates one path from the next in the list.
eg: PATH = : / bin : / usr / bin : / usr /s4c
echo $ PATH
2. LOGNAME - Describes the login name
eg : echo $LOGIN
3. HOME - Describes the path of the user’s home directory.
eg: echo $ HOME
4. PWD - Stores present working directory
5. SHELL - Stores the path to the shell program that is being used.
Eg: SHELL = /bin/bash
6. MAIL - stores path to the current users mail box.
We can see them by using the command env. We can change our variable to environment variable by using
export command.
Rules for naming 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 ( _).
1. Begin with alphanumeric characters or under score ( _ ) followed by one or more alphanumeric
characters.
2. Values are case sensitive.
3. Don’t use special characters.
Null variables can be defined as $v=““.
Don’t put space on either side of the equal ( = ) sign.
To access the value stored in a variable, prefix its name with the dollar sign ($)

Example (shell script):


1. The following shell script uses the read command which takes the input from the keyboard and
assigns it to the variable ‘PERSON’ and prints it on the screen.
echo “What is your name ? “
read PERSON
echo “ Hello , $ PERSON”

2. To create a script containing 2 commands


# Two commands
pwd
ls

[ How to run a shell script?


1. Create a new script file with .sh extension using a text editor like pico or gedit.
2. To execute shell script use the command sh script-name.sh
or bash script-nam.sh ]

Arithmetic operators
1. + - addition $a+$b
2. - - subtraction $a-$b
3. * - Multiplication $ a \* $ b
4. / - Division $a\/$b
5. % - remainder of Division
Relational Operators
1. – eq - Equals
2. – ne - not equal to
3. – gt - greater than
4. – ge - greater than or equal to
5. – lt - less than
6. – le - less than or equal to
Logical operators
1. – a - AND
2. – o - OR
Quotes: There are 3 types of quotes
1. “ - double quotes
2. ‘ - single quotes
3. ` - back quotes
Control Structures:
( Explain decision making and branching statements with examples. 15 marks May 23)
1. if - Simple if is used for decision making in shell script. If the given condition is true, then it will execute
the code inside the block.
Syntax:
if [ condition ]
then
statements
fi
eg: # Check number is 1
echo “ enter a number “
read no
if [ $ no – eq 1 ]
then
echo “ number 1”
fi
2. if … else - it is also used for decision making. If the condition is true, then it will execute the statements in the
true block; otherwise it will execute the false block.
Syntax:
if [ condition ]
then
statements
else
statements
fi
eg: # Check number is positive or not
echo “ enter a number “
read no
if [ $ no –gt 0 ]
then
echo “ number is positive “
else
echo “ number is negative “
fi

3. if … elif - It is possible to create compound conditional statements using els .. if (elif). If the 1st condition is true,
then the true part is executed. Otherwise, the 2nd condition is checked. If the 2nd condition is true, the true part of elif is
executed.
Syntax: if [ condition ]
then
statements
elif [ condition ]
then
statements
fi
eg: Check + ve or - ve
echo “ enter a number “
read n
if [ $ n –gt 0 ]
then
echo “ Positive “
elif [ $ n –lt 0 ]
then
echo “ Negarive “
fi
(Qn: Rating check)

4. If .. elif … else - if the condition1 is true, then the true block is executed. If the condition 2 is true, then the
true block of elif is to be executed. Otherwise the else block is to be executed.
Syntax: if [ condition1 ]
then
statements
elif [ condition 2 ]
then
statements
else
statements
fi
eg: Check + ve or - ve or 0
echo “ enter a number “
read n
if [ $ n –gt 0 ]
then
echo “ Positive “
elif [ $ n –lt 0 ]
then
echo “ Negarive “
else
echo “ zero “
fi
5. if – elif ladder - It is a series of if statements. Here each if is a part of the else clause of the previous if. Here
statements are executed based on the true condition. If none of the conditions is true then the else block is executed.
Syntax : if [ condition ]
then
statements
elif [ condition ]
then
statements
elif [ condition ]
then
statements
.
.
.
else
statements
fi
eg: print day name corresponding to day number
echo “ Enter a number between 1 and 7 “
read n
if [ $n – eq 1]
then
echo “ Sunday “
elif [ $n – eq 2 ]
then
echo “ Monday “
elif [ $n – eq 3 ]
then
echo “ Tuesday “
elif [ $n – eq 4 ]
then
echo “ Wednesday “
elif [ $n – eq 5 ]
then
echo “Thursday “
elif [ $n – eq 6 ]
then
echo “ Friday “
elif [ $n – eq 7 ]
then
echo “Saturday “
else
echo “ Not valid “
fi
6. Nested if statement : When an if statement contains many elif constructs then we say that it is a nested if statement.
Syntax:
if [ condition]
then
statements
else
if [ condition]
then
statements
fi
fi
eg: Check for user name and password
echo "Enter your Name"
read name
if [ $name = "Arun" ]
then
echo "Enter Password"
read pass
if [ $pass = "abcd" ]
then
echo "Hello $name"
else
echo "Wrong password"
fi
else
echo "wrong username"
fi
Eg 2: find the biggest among 3 numbers

(Give syntax of case statement. 2 marks May 23)


7. case - case statements are used to transfer the control to one of multiple statements. Case statements are used
instead of if…elif ladder.
Syntax: case exp in
pattern1 ) statements ; ;
pattern2 ) statements ; ;
pattern3 ) statements ; ;
.
.
.
*) statements ; ;
esac
The pattern is evaluated and the control is switched to the statements matching any of the patterns. If none of the
pattern is matched, then the control goes to statements following ‘ * ‘.

eg: # Accept the day number of a week and display day name
echo “ Enter a number between 1 and 7 “
read n
case $n in
1 ) echo “Sunday “ ; ;
2 ) echo “Monday “ ; ;
3 ) echo “Tuesday “ ; ;
4 ) echo “Wednesday “ ; ;
5 ) echo “Thursday “ ; ;
6 ) echo “Friday “ ; ;
7 ) echo “Saturday “ ; ;
* ) echo “Invalid Day Number“ ; ;
esac
Read a character and display whether it is vowel or not
echo “ Enter a Character “
read c
case $c in
[ a e i o u A E I O U ] ) echo “ It is vowel “ ; ;
* ) echo “ Not a vowel “ ; ;
esac

Looping Statements
1. while - It is used to repeatedly execute a set of statements any number of times when a condition is true until the
condition evaluates to false..
Syntax : while [ condition ]
do
statements
done
eg: # write a shell script to display integers from 1 to 10
i =1
while [ $ i - le 10 ]
do
echo $ i
i = `expr $ i + 1 `
done
2. until - It is used to execute a set of commands repeatedly until a condition is true. It is an inversion of the while
loop. Syntax: until [ condition ]
do
statements
done
eg: # To display numbers from 1 to 10
i =1
until [ $ i - gt 10 ]
do
echo $ i
i = ‘ expr $ i + 1 ‘
done
3. for Syntax (1): for variable_name in list
do
statements
done
For each value in the list, the variable_name gets the value and the loop is executed.

eg (i): # to print the numbers 1 3 5 7 10


for i in 1 3 5 7 10
do
echo $ i
done

(ii): # to print numbers from 1 to 5


echo “Enter a number”
read no
for no in {1..5}
do
echo $ no
done

(iii) # to print numbers from 1 to 50 in steps of 5


for n in {1..50..5}
do
echo $n
done

Note: for , do , done, in are keywords

Syntax (2): for (( expn 1 ; expn 2; expn 3 ))


do
statements
done

This syntax is similar to the syntax of for statement in C++ language. expn1 is executed 1st for initialization. expn2 is
executed next for checking condition. If it is true, the loop is executed. Then expn3 is executed for incrementation or
decrementation of the loop control variable. Then the loop is repeated if expn 2 is evaluated to true, and so on.
eg: for ((i = 1 ; i < 10; i ++ ))
do
echo $ i
done
Control Statements used in looping statements

1. break - The break statement is used to terminate the execution of the loop and transfer the control
to the statement after the end of the loop.
Syntax 1): break
Used to exit from the loop
Syntax 2): break n
Used to exit from a nested loop. ‘n’ specifies the number of loops to be exited.
eg: a=0
while [ $a –lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a= ‘ expr $a + 1’
done
2. continue - It is used to transfer the control to the next iteration of the loop, ignoring the remaining
porttion of the current iteration.
Syntax 1): continue
Syntax 2): continue n
Here ‘ n ‘ specifies the nth enclosing loop to continue.
Eg: # to display odd numbers from a list
NUMS = “ 1 2 3 4 5 6 7 “
for NUM in NUMS
do
Q = ‘ expr $ NUM % 2 ‘
if [ $Q - eq 0 ]
then
continue
fi
echo $i
done

Passing Arguments to the Shell Script / Command Line Arguments


(Parameter passing & arguments)
What is command line argument? How will you use command line arguments in a
shell?
Command-line arguments are parameters that are passed to a script while executing
them in the bash shell. They are also known as positional parameters in Linux.
We use command-line arguments to denote the position in memory where the
command and it's associated parameters are stored.
Command-line arguments are passed in the positional way i.e. in the same way
how they are given in the program execution. To pass command line arguments, we
can write them after the script name separated with space.
eg: sh file.sh 10 20 30
Maximum length of command line parameters are not defined by shell, but by the OS.
Positional Parameters
They are a series of special variables( $1, $2,…) that contain the contents of the command line.
$1 - references 1st command line argument.
$2 - references 2nd command line argument.
..........
..........
$o - references name of the script.
$* - references all command line arguments.
$@ - references all command line arguments.
$# - references count of command line arguments.
eg 1: sh file.sh 10 20 30
echo “ Script name : $o”
echo “ Total number of arguments: $ #”
echo “ Argument list : “
echo “ 1. $ 1 “
echo “ 2. $ 2 “
echo “ 3. $ 3 “
echo “ All arguments are : $ * “

eg 1: # To find large value accepted from command line arguments.


if [ $ 1 - gt $ 2 ]
then
echo “ large is $ 1 “
else
echo “ large is $ 2 “
fi
To run : sh large 89 23

Question: Explain function in shell with suitable example. How will you pass parameters in shell?
Answer: A function is a block of code that carries out a certain activity. A function can be called and reused.
Syntax:
function_name ()
{
list of commands
}
Example :
Hello () {
echo "Hello World"
}
Save the script above in your Linux system as test.sh and then run it in the terminal by writing ./test.sh

You can define a function that will accept parameters while calling the function. These parameters
would be represented by $1, $2 and so on.
Following is an example where we pass two parameters Zara and Ali and then we capture and
print these parameters in the function.
Example :
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
Upon execution, you will receive the following result −

$./test.sh
Hello World Zara Ali

Question: Write a shell script to copy all files with .c extension in the current working directory to a
subdirectory.
Answer : cp *.c /program

Shell Keywords in Linux:


Keywords are the words whose meanings are already explained to the shell. The keywords can’t be used as variable
names. Following are some keywords used in Linux

echo if while exit umask


read else do return ulimit
set elif done for trap
unset fi until exec
shift case break eval
export esac continue wait

Automating System Tasks


Tasks (jobs) can be configured to run automatically within a specific period of time, or on a specific date, or when the
system load average decreases below a specific value. The automated task utilities are : - cron, anacron, at and batch.
1. anacron - cron and ancron are daemons that can schedule execution of recurring tasks at the exact time,
day of the month, month, day of the week and week.
cron jobs can run as often as every minute. If the system is not running at the time when the job is scheduled.
The job is then executed as soon as the system is up. Anacron can only run a job only once a day.
eg: A simple etc / anacron tab file
SHELL = / bin / sh
PATH = / bin :/ usr /bin : / sbin
MAIL TO = root
RANDOM_DELAY = 30
START_HOURS_RANGE = 16 – 20
Period in days Delay in Minutes Job identifier Command

1 20 Daily job ls home/tmp/proc


7 25 Weekly job /etc/weeklyjob.sh

1st three lines define the variables that configure the environment.
● SHELL - Shell environment used for running jobs
● PATH - Path to execute the programs
● MAILTO -usernames of the users who receive the output of the anacrons jobs by email.
The next 2 variables modify the scheduled time for the defined jobs.
● RANDOM_DELAY – Maximum number of minutes that will be added to the delay. If the time is missed,
the scheduled jobs are not executed on the day.
The remaining lines are in the following format:-
● Period in days – Frequency of job execution in days.
● Delay in minutes – number of minutes to wait before executing the job.
● Job identifier – unique name of a particular job.
● Command - the command to be executed.
2. cron - Configuration files for cron jobs are in the etc/crontab, which can only be modified by the root user.
The file contains the following:
The 1st three lines contain the SHELL, PATH and MAILTO variables. In addition, the file can contain HOME
variable. The home variable defines the home directory. The remaining lines have the following format:-
Minute hour day month day of week user name command
Minute - integer from 0 -59
Hour - 0 – 23
Day - 1 – 31
Month - 1 – 12
Day of week - 0–7
User name - specifies the user
Command - commands to be executed
* can be used to specify all valid values.
Any line beginning with # are comments and are not processed.
To create a crontab, use the command:-
crontab –e : to edit
eg:
29 0 * * * / usr / bin /example
To run the command /usr / bin / example at 12.30 everyday.

3. at, batch - Refer scheduling commands.

You might also like