Shell Programming
Shell Programming
What is Kernel?
• A shell is a special user program that provides an interface for the user to use
operating system services.
• Shell accepts human-readable commands from users and converts them into
something which the kernel can understand.
• It is a command language interpreter that executes commands read from
input devices such as keyboards or from files.
• The shell gets started when the user logs in or starts the terminal.
Shell
• BASH (Bourne Again SHell) – It is the most widely used shell in Linux
systems. It is used as default login shell in Linux systems and in macOS. It can
also be installed on Windows OS.
• CSH (C SHell) – The C shell’s syntax and its usage are very similar to the C
programming language.
• KSH (Korn SHell) – The Korn Shell was also the base for the POSIX Shell
standard specifications etc.
Shells
• Shells are interactive, which means they accept commands
as input from users and execute them.
• Each shell script is saved with `.sh` file extension
e.g., myscript.sh.
• How to Create a Shell Script in linux
Cat > filename.sh
(or)
Vi filename.sh
(or)
touch filename.sh
(or)
Nano filename.sh
Shell
• Save the changes, and run the shell script by typing in
./script.sh
(or)
sh filename.sh
• Operator Description
• -eq is equal to
• -ne is not equal to
• -gt is greater than
• -ge is greater than or equal to
• -lt is less than
• -le is less than or equal to
String Comparison
• Operator Description
• == is equal to
• != is not equal to
• \< is less than, in ASCII alphabetical order
• \> is greater than, in ASCII alphabetical order
Conditional statements
If statement
It checks the condition, and if it is conditioned true, it executes the
commands.
Syntax
if [ condition ]
then
#statements
fi
Let’s see an example.
#!/bin/sh
x=10
y=11
if [ $x -ne $y ]
then
echo "Not equal"
fi
If-else statement
In an if-else statement, you can specify a set of commands to run if the condition is not
met.
Syntax
if [ condition ]
then
#set of statements if the condition is true
else
#set of statements if the condition is false
fi
Let’s see an example.
x=10
y=10
if [ $x -ne $y ]
then
echo "Not equal"
else
echo "They are equal"
fi
Loops
While loop
It starts running the specified commands if the condition is true and repeats
them until the condition is false.
Syntax
while [ condition ]
do
#set of statements
done
Example
x=2
while [ $x -lt 6 ]
do
echo $x
x=`expr $x + 1`
done
expr command in Linux with
examples
The expr command in Unix evaluates a given expression
and displays its corresponding output. It is used for:
• Basic operations like addition, subtraction,
multiplication, division, and modulus on integers.
• Evaluating regular expressions, string operations like
substring, length of strings etc.
Syntax:
$expr expression
For loop
Syntax
if [ $a -gt 40 -a $b -lt 6 ]