0% found this document useful (0 votes)
12 views23 pages

Os Module II

Module II covers Linux shell programming, emphasizing the importance of shell scripting for UNIX system administrators to automate tasks and modify installation scripts. It explains the roles of the kernel and shell, differentiates between command line and graphical shells, and lists various types of shells available in UNIX. Additionally, it discusses the Linux directory layout, common shell commands, advantages and disadvantages of shell scripts, and provides examples of shell usage and navigation commands.

Uploaded by

ak4athulkrishna
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)
12 views23 pages

Os Module II

Module II covers Linux shell programming, emphasizing the importance of shell scripting for UNIX system administrators to automate tasks and modify installation scripts. It explains the roles of the kernel and shell, differentiates between command line and graphical shells, and lists various types of shells available in UNIX. Additionally, it discusses the Linux directory layout, common shell commands, advantages and disadvantages of shell scripts, and provides examples of shell usage and navigation commands.

Uploaded by

ak4athulkrishna
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/ 23

MODULE II

LINUX SHELL PROGRAMMING

Introduction
Shell programming is a basic skill that every UNIX System administrator
should have. The Systems Administrator must be able to read and write
shell programs because
 There are many tasks that can and should be quickly automated by
using shell programs
 Many software products come with install scripts that have to be
modified for our system before they will work.

A Kernel is at the nucleus of a computer. It makes the


communication between the hardware and software possible. While the
Kernel is the innermost part of an operating system, a shell is the outermost
one. A shell in a Linux operating system takes input from we in the form of
commands, processes it, and then gives an output. It is the interface
through which a user works on the programs, commands, and scripts. A
shell is accessed by a terminal which runs it.

When we run the terminal, the Shell issues a command prompt


(usually $), where we can type our input, which is then executed when we
hit the Enter key. The output or the result is thereafter displayed on the
terminal. The Shell wraps around the delicate interior of an Operating
system protecting it from accidental damage. Hence the name Shell.

If we are using any major operating system we are indirectly


interacting to shell. If we are running Ubuntu, Linux Mint or any other
Linux distribution, we are interacting to shell every time we use terminal. In
this article I will discuss about linux shells and shell scripting so before
understanding shell scripting we have to get familiar with following
terminologies –
 Kernel
 Shell
 Terminal

What is Kernel
The kernel is a computer program that is the core of a computer’s operating
system, with complete control over everything in the system. It manages
following resources of the Linux system –
 File management
 Process management
 I/O management
 Memory management
 Device management etc.
It is often mistaken that Linus Torvalds has developed Linux OS,
but actually he is only responsible for development of Linux kernel.
Complete Linux system = Kernel + GNU system utilities and libraries + other
management scripts + installation scripts.

What is Shell
A shell is special user program which provide an interface to user
to use operating system services. Shell accept human readable commands
from user and convert them into something which kernel can understand. It
is a command language interpreter that execute commands read from input
devices such as keyboards or from files. The shell gets started when the user
logs in or start the terminal.

Linux Shell

Shell is broadly classified into two categories –


1. Command Line Shell
2. Graphical shell

Command Line Shell


Shell can be accessed by user using a command line interface. A
special program called Terminal in linux/macOS or Command Prompt in
Windows OS is provided to type in the human readable commands such as
“cat”, “ls” etc. and then it is being execute.
Graphical Shells
Graphical shells provide means for manipulating programs based
on graphical user interface (GUI), by allowing for operations such as
opening, closing, moving and resizing windows, as well as switching focus
between windows. Window OS or Ubuntu OS can be considered as good
example which provide GUI to user for interacting with program. User do not
need to type in command for every actions.

There are several shells are available for Linux systems like –
 BASH (Bourne Again SHell) – It is 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 usage are very similar to the
C programming language.
 KSH (Korn SHell) – The Korn Shell also was the base for the POSIX
Shell standard specifications etc.
Each shell does the same job but understands different commands and
provide different built in functions.

SHELLS AVAILABLE IN UNIX


A shell is a user program that allows the user to specify operations
in a certain sequence. As we discussed in last post about what is shell in
UNIX. Now we will discuss about all different type of shell available in UNIX.
If all shell available on our system then we can switch between different
shells. Following are different types of shells –

1. Bourne Shell (sh) – Bourne Shell is the original unix shell developed at
AT&T by Stephen Bourne. Bourne shell also named as (sh) programming
name. It used the symbol $. Bourne shell’s family is bourne, korn shells,
bash and zsh .
2. Korn shell (ksh) – korn shell is the unix shell developed by David korn
of Bell labs. Is is considered as the family member of Bourne shell as it
uses the $ symbol of Bourne shell. It is also names as ksh programmatic
ally and it most widely used shell.
3. Bourne Again Shell (bash) – It is the free version of Bourne shell and
comes with all UNIX/Linux systems as free with some additional features
like command line editing. Its program name is bash. It can read
commands from file called scripts.

Like all Unix shells it supports the following:


 File name wildcarding
 Piping
 Hear documents
 Command execution
 Variables and control structures for condition testing and iteration

4. C Shell (sh) – C shell is the UNIX shell created by Bill joy at California
university as an alternative to Bourne shell – Unix original shell. C shell
along with Bourne and Korn, are there most popular and commonly used
shells. csh is the program name for C shell.

5. Tab C Shell (tcsh) – It is the family member of C shell with additional


features like enhanced history substitution to reuse commands, spelling
correction and word completion.

Hello World Example


Create a file first.sh
#! /bin/sh
echo Hello World
Now run –
./first.sh
Output will be – Hello World

Working with VI editor – VI is main editor to work on unix systems.


There are 3 main command mode on vi editor.
Command Mode – Keys works as command like insert, delete, moving to
new line etc. We can not edit or type in command mode.
Insert Mode – To write anything in script, press I or A for insert mode.
Execution Mode – This mode is used to execute that we have done. Like to
save changes, first press escape key then type colon and wq.
Vi editor saving and quitting commands:
:w -Save the contents of the file.
:q – Quit from vi editor.
:q! -quit from vi editor by discarding any changes.
:wq -Save the file and quit from the vi editor.

BASH: SPECIAL CHARACTERS


Here are some of the more common special characters uses:
Character Description
Whitespace — this is a tab, newline, vertical tab, form feed,
carriage return, or space. Bash uses whitespace to determine
"" where words begin and end. The first word is the command
name and additional words become arguments to that
command.
Expansion — introduces various types of expansion: parameter
expansion (e.g. $var or ${var}), command
$
substitution (e.g. $(command)), or arithmetic expansion
(e.g. $((expression))). More on expansions later.
Single quotes — protect the text inside them so that it has
a literal meaning. With them, generally any kind of
''
interpretation by Bash is ignored: special characters are
passed over and multiple words are prevented from being split.
Double quotes — protect the text inside them from being split
""
into multiple words or arguments, yet allow substitutions to
occur; the meaning of most other special characters is usually
prevented.
Escape — (backslash) prevents the next character from being
interpreted as a special character. This works outside of
\
quoting, inside double quotes, and generally ignored in single
quotes.
Comment — the # character begins a commentary that extends
# to the end of the line. Comments are notes of explanation and
are not processed by the shell.
Assignment -- assign a value to a variable
= (e.g. logdir=/var/log/myprog). Whitespace is not allowed on
either side of the = character.
Test — an evaluation of a conditional expression to determine
whether it is "true" or "false". Tests are used in Bash to
[[ ]]
compare strings, check the existence of a file, etc. More of this
will be covered later.
Negate — used to negate or reverse a test or exit status. For
!
example: ! grep text file; exit $?.
Redirection — redirect a command's output or input to a file.
>, >>, <
Redirections will be covered later.
Pipe — send the output from one command to the input of
| another command. This is a method of chaining commands
together. Example: echo "Hello beautiful." | grep -o beautiful.
Command separator — used to separate multiple commands
;
that are on the same line.
Inline group — commands inside the curly braces are treated
as if they were one command. It is convenient to use these
{}
when Bash syntax requires only one command and a function
doesn't feel warranted.
Subshell group — similar to the above but where commands
within are executed in a subshell (a new process). Used much
()
like a sandbox, if a command causes side effects (like changing
variables), it will have no effect on the current shell.
Arithmetic expression — with an arithmetic expression,
characters such as +, -, *, and / are mathematical operators
(( )) used for calculations. They can be used for variable
assignments like (( a = 1 + 4 )) as well as tests like if (( a < b )).
More on this later.
Arithmetic expansion — Comparable to the above, but the
$(( )) expression is replaced with the result of its arithmetic
evaluation. Example: echo "The average is $(( (a+b)/2 ))".
*, ? Globs -- "wildcard" characters which match parts of filenames
(e.g. ls *.txt).
Home directory — the tilde is a representation of a home
directory. When alone or followed by a /, it means the current
~
user's home directory; otherwise, a username must be
specified (e.g. ls ~/Documents; cp ~john/.bashrc .).
Background -- when used at the end of a command, run the
&
command in the background (do not wait for it to complete).

Examples:
$ echo "I am $LOGNAME"
I am lhunath
$ echo 'I am $LOGNAME'
I am $LOGNAME
$ # boo
$ echo An open\ \ \ space
An open space
$ echo "My computer is $(hostname)"
My computer is Lyndir
$ echo boo > file
$ echo $(( 5 + 5 ))
10
$ (( 5 > 0 )) && echo "Five is greater than zero."
Five is greater than zero.

GETTING HELP
Type help after almost any command to bring up a help menu for that
command:
help:- The help command provides information on built-in commands.

help pwd:- At the prompt, enter ‘help’ followed by the command we wish to
learn more about.

help –d pwd:- With the ‘-d’ option, the help command will only return a
short description of the specified command.

help –s pwd:- With the -s option, help will return a short usage synopsis for
the specified command.

help –m pwd:- If we prefer the look of manpages, then we’ll be happy to


know that the ‘-m’ option formats the help command output as a pseudo-
manpage.

MAN PAGES
Type man before almost any command to bring up a manual for
that command. The man command in Linux is used to display the user
manual of any command that we can run on the terminal. It provides a
detailed view of the command which includes NAME, SYNOPSIS,
DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS,
FILES, VERSIONS, EXAMPLES, and AUTHORS.
Syntax :
$man [OPTION]... [COMMAND NAME]...
Example
$ man printf
$ man 2 intro
$ man -a intro
$ man -k cd
$ man -f ls

Advantages of shell scripts


 The command and syntax are exactly the same as those directly
entered in command line, so programmer do not need to switch to
entirely different syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.

Disadvantages of shell scripts


 Prone to costly errors, a single mistake can change the command
which might be harmful
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting languages. etc

LINUX DIRECTORY LAYOUT


The Linux File Hierarchy Structure or the File system Hierarchy
Standard (FHS) defines the directory structure and directory contents in
Unix-like operating systems. It is maintained by the Linux Foundation.

 In the FHS, all files and directories appear under the root directory /,
even if they are stored on different physical or virtual devices.
 Some of these directories only exist on a particular system if certain
subsystems, such as the X Window System, are installed.
 Most of these directories exist in all UNIX operating systems and are
generally used in much the same way; however, the descriptions here
are those used specifically for the FHS, and are not considered
authoritative for platforms other than Linux.

Each of the above directories (which is a file, at the first place)


contains important information, required for booting to device drivers,
configuration files, etc. Describing briefly the purpose of each directory, we
are starting hierarchically.
 /bin : All the executable binary programs (file) required during
booting, repairing, files required to run into single-user-mode, and
other important, basic
commands viz., cat, du, df, tar, rpm, wc, history, etc.
 /boot : Holds important files during boot-up process, including Linux
Kernel.
 /dev : Contains device files for all the hardware devices on the
machine e.g., cdrom, cpu, etc
 /etc : Contains Application’s configuration
files, startup, shutdown, start, stop script for every individual
program.
 /home : Home directory of the users. Every time a new user is created,
a directory in the name of user is created within home directory which
contains other directories like Desktop, Downloads, Documents, etc.
 /lib : The Lib directory contains kernel modules and shared
library images required to boot the system and run commands in root
file system.
 /lost+found : This Directory is installed during installation of Linux,
useful for recovering files which may be broken due to
unexpected shut-down.
 /media : Temporary mount directory is created for removable devices
viz., media/cdrom.
 /mnt : Temporary mount directory for mounting file system.
 /opt : Optional is abbreviated as opt. Contains third party application
software. Viz., Java, etc.
 /proc : A virtual and pseudo file-system which contains information
about running process with a particular Process-id aka pid.
 /root : This is the home directory of root user and should never be
confused with ‘/‘
 /run : This directory is the only clean solution for early-runtime-
dir problem.
 /sbin : Contains binary executable programs, required by System
Administrator, for Maintenance. Viz., iptables, fdisk, ifconfig, swapon,
reboot, etc.
 /srv : Service is abbreviated as ‘srv‘. This directory contains server
specific and service related files.
 /sys : Modern Linux distributions include a /sys directory as a virtual
filesystem, which stores and allows modification of the devices
connected to the system.
 /tmp :System’s Temporary Directory, Accessible by users and root.
Stores temporary files for user and system, till next boot.
 /usr : Contains executable binaries, documentation, source
code, libraries for second level program.
 /var : Stands for variable. The contents of this file is expected to grow.
This directory contains log, lock, spool, mail and temp files

COMMAND FOR NAVIGATING THE LINUX FILE SYSTEMS


The following commands are used to navigate the system
Pwd:- To find the name of the working directory
cd:- To move around the file system use the cd command.
ls:- To list files and directories
file:- to identifies the file type (binary, text, etc)
cat:- To Displays a filename
cp:- To Copies one file/directory to the specified location
mv:- To Moves the location of, or renames a file/directory
mkdir:- To Creates the specified directory
rmdir:- To Removes a directory
whereis:- To Shows the location of a file

PIPING AND REDIRECTION


UNIX commands and files can be used in conjunction with one
another to turn simple commands into much more complex commands.
When these conjunctions involve files, we call it redirection. When these
conjunctions involve commands we call it piping. Piping and redirection is
the means by which we may connect these streams between programs and
files to direct data in interesting and useful ways.
Pipes allow us to funnel the output from one command into
another where it will be used as the input. In other words, the standard
output from one program becomes the standard input for another. The
“more” command takes the standard input and paginates it on the standard
output (the screen). This means that if a command displays more
information than can be shown on one screen, the “more” program will
pause after the first screen full (page) and wait for the user to press SPACE
to see the next page or RETURN to see the next line.

Here is an example which will list all the files, with details (-la) in
the /dev directory and pipe the output to more. The /dev directory should
have dozens of files and hence ensure that more needs to paginate.

ls -la /dev | more

Notice the --More-- prompt at the bottom of the screen. Press SPACE to see
the next page and keep pressing SPACE until the output is finished.
Here is another pipe example, this time using the “wc” (word count) tool.
ls -1 /dev | wc

wc counts the numbers of lines, words and characters in the standard


input. If we use the -l parameter it will display only the number of lines,
which is good way to see how many files are in a directory!

Redirection is similar to pipes except using files rather than


another program. The standard output for a program is the screen. Using
the > (greater than) symbol the output of a program can be sent to a file.
Here is a directory listing of /dev again but this time redirected to a file
called listing.txt
ls -la > listing.txt

There won’t be anything displayed on the terminal as everything was sent to


the file. We can take a look at the file using the cat command (which can be
piped into more) or for convenience we can just use the more command on
its own:
more listing.txt

If listing.txt had already existed, it will be overwritten. But we can append to


an existing file using >> like this:
ls -la /home > listing.txt
ls -la /dev >> listing.txt

The first redirection will overwrite the file listing.txt while the
second will append to it. Now whatever text we type will be sent to the
file atextfile.txt until we press Control-D, at which point the file will be
closed and we will be returned to the command prompt. If we want to add
more text to the file use the same command but with two greater than signs
(>>).
INFORMATIONAL COMMANDS
 ps:- ps shows process status. Use this command to displays a table of
all our own running programs or processes
 w:- Used to show who is logged on and what they are doing
 id:- Used to find out user and group names and numeric ID’s (UID or
group ID) of the current user or any other user in the server
 free:- Displays the total amount of free space available along with the
amount of memory used and swap memory in the system, and also the
buffers used by the kernel
 clear:- Used to clear the terminal screen
 echo:- Used to display line of text/string that are passed as an
argument
 more:- Used to view the text files in the command prompt, displaying
one screen at a time in case the file is large (For example log files)

FILE PERMISSIONS
Every file and directory in our UNIX/Linux system has following 3
permissions defined for all the 3 owners (User, Group, Other).

 Read: This permission give we the authority to open and read a file.
Read permission on a directory gives we the ability to lists its content.
 Write: The write permission gives we the authority to modify the
contents of a file. The write permission on a directory gives we the
authority to add, remove and rename files stored in the directory.
Consider a scenario where we have to write permission on file but do
not have write permission on the directory where the file is stored. We
will be able to modify the file contents. But we will not be able to
rename, move or remove the file from the directory.
 Execute: In Windows, an executable program usually has an
extension ".exe" and which we can easily run. In Unix/Linux, we
cannot run a program unless the execute permission is set. If the
execute permission is not set, we might still be able to see/modify the
program code(provided read & write permissions are set), but not run
it.

Setting Permissions
 chmod +rwx filename to add permissions.
 chmod -rwx directoryname to remove permissions.
 chmod +x filename to allow executable permissions.
 chmod -wx filename to take out write and executable permissions.
CREATING SHELL PROGRAMS
For creating Shell programs we need to identify some terminologies

COMMENTS
When we are writing shell programs as a Systems Administrator
comments are doubly important. Chances are won't be at the site forever. At
some stage another Systems Administrator is going to come along and have
to decipher what our shell programs are doing.

Shell programs use the # character to signify comments. Anything


after a # character until the end of the line is considered a comment and is
ignored by the shell.

Example
#!/bin/bash
# A Simple Shell Script To Get Linux Network Information
# Vivek Gite - 30/Aug/2009
echo "Current date : $(date) @ $(hostname)"
echo "Network configuration"

VARIABLES
A variable is declared without a $, but has a $ when invoked. Let's
edit our hello-world example to use a variable for the entity being greeted,
which is World.

#!/bin/bash
who="World"
echo Hello, $who!
OPERATORS
1. Arithmetic Operators

+ (Addition) Adds values on either side of the operator


– (Subtraction) Subtracts right hand operand from left hand operand
* (Multiplication) Multiplies values on either side of the operator
/ (Division Divides left hand operand by right hand operand
% (Modulus) Divides left hand operand by right hand operand and
returns remainder
(++) Increment Unary operator used to increase the value of operand
Operator by one.
(--) Decrement unary operator used to decrease the value of a operand
Operator by one

Example
#!/bin/sh
a=5
b=10
val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

Relational operators
Relational operators are those operators which defines the relation
between two operands. They give either true or false depending upon the
relation. They are of 6 types:
‘==’ Operator : Double equal to operator compares the two operands. Its
returns true is they are equal otherwise returns false.
‘!=’ Operator : Not Equal to operator return true if the two operands are not
equal otherwise it returns false.
‘<' Operator : Less than operator returns true if first operand is lees than
second operand otherwse returns false.
‘<=' Operator : Less than or equal to operator returns true if first operand is
less than or equal to second operand otherwise returns false
‘>’ Operator : Greater than operator return true if the first operand is
greater than the second operand otherwise return false.
‘>=’ Operator : Greater than or equal to operator returns true if first
operand is greater than or equal to second operand otherwise returns false

Example
#!/bin/bash
#reading data from the user
read -p 'Enter a : ' a
read -p 'Enter b : ' b
if(( $a!=$b ))
then
echo a is not equal to b.
else
echo a is equal to b.
fi
if(( $a<=$b ))
then
echo a is less than or equal to b.
else
echo a is not less than or equal to b.
fi

LOGICAL OPERATORS
They are also known as boolean operators. These are used to perform logical
operations. They are of 3 types:
1. Logical AND (&&) : This is a binary operator, which returns true if
both the operands are true otherwise returns false.
2. Logical OR (||) : This is a binary operator, which returns true is
either of the operand is true or both the operands are true and returns
false if none of then is false.
3. Not Equal to (!) : This is a uninary operator which returns true if the
operand is false and returns false if the operand is true.

Example
#!/bin/bash
#reading data from the user
read -p 'Enter a : ' a
read -p 'Enter b : ' b

if(($a == "true" & $b == "true" ))


then
echo Both are true.
else
echo Both are not true.
fi
if(( ! $a == "true" ))
then
echo "a" was intially false.
else
echo "a" was intially true.
fi

SINGLE QUOTES
Use single quote when we want to literally print everything inside
the single quote. Even the special variables such as $HOSTNAME will be
print as $HOSTNAME instead of printing the name of the Linux host.
$ echo 'Hostname=$HOSTNAME ;
Current User=`whoami` ;
Message=\$ is USD'
Hostname=$HOSTNAME ;
Current User=`whoami` ;
Message=\$ is USD

DOUBLE QUOTES
Use double quotes when we want to display the real meaning of special
variables.
$ echo "Hostname=$HOSTNAME ;
Current User=`whoami` ;
Message=\$ is USD"
Hostname=dev-db ;
Current User=ramesh ;
Message=$ is USD

Double quotes will remove the special meaning of all characters except the
following:
$ Parameter Substitution.
` Backquotes
\$ Literal Dollar Sign.
\´ Literal Backquote.
\” Embedded Doublequote.
\\ Embedded Backslashes.

CONDITIONAL COMMANDS
There are total 5 conditional statements which can be used in bash
programming
1. if statement
2. if-else statement
3. if..elif..else..fi statement (Else If ladder)
4. if..then..else..if..then..fi..fi..(Nested if)
5. switch statement
Their description with syntax is as follows

If statement
This block will process if specified condition is true.

Syntax:
if [ expression ]
then
statement
fi
if-else statement
If specified condition is not true in if part then else part will be execute.

Syntax
if [ expression ]
then
statement1
else
statement2
fi

if..elif..else..fi statement (Else If ladder)


To use multiple conditions in one if-else block, then elif keyword is
used in shell. If expression1 is true then it executes statement 1 and 2, and
this process continues. If none of the condition is true then it processes else
part.
Syntax
if [ expression1 ]
then
statement1
statement2
.
elif [ expression2 ]
then
statement3
statement4
.
else
statement5
fi

if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies
then it again checks another condition. In the syntax, if expression1 is false
then it processes else part, and again expression2 will be check.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
Switch Statement
The case statement works as a switch statement if specified value
match with the pattern then it will execute a block of that particular pattern
When a match is found all of the associated statements until the double
semicolon (;;) is executed. A case will be terminated when the last command
is executed. If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac

Example 1 Example 2
#Initializing two variables #Initializing two variables
a=10 a=20
b=20 b=20

#Check whether they are equal if [ $a == $b ]


if [ $a == $b ] then
then #If they are equal then print
echo "a is equal to b" this
fi echo "a is equal to b"
else
#Check whether they are not equal #else print this
if [ $a != $b ] echo "a is not equal to b"
then fi
echo "a is not equal to b"
fi

Example
CARS="bmw"
#Pass the variable in string
case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach,
Germany" ;;

#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;

#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu,
India" ;;
esac
ITERATIVE COMMANDS
There are total 2 looping statements which can be used in bash
programming
1. while statement
2. for statement

While Statement
Here command is evaluated and based on the result loop will
executed, if command raise to false then loop will be terminated
Syntax
while command
do
Statement to be executed
done
For Statement
The for loop operate on lists of items. It repeats a set of commands for
every item in a list. Here var is the name of a variable and word1 to wordN
are sequences of characters separated by spaces (words). Each time the for
loop executes, the value of the variable var is set to the next word in the list
of words, word1 to wordN.

Syntax
for var in word1 word2 ...wordn
do
Statement to be executed
done
Example 1 Example 1
#Start of for loop for a in 1 2 3 4 5 6 7 8 9 10
for a in 1 2 3 4 5 6 7 8 9 10 do
do # if a = 5 then continue the
# if a is equal to 5 break the loop loop and
if [ $a == 5 ] # don't move to line 8
then if [ $a == 5 ]
break then
fi continue
# Print the value fi
echo "Iteration no $a" echo "Iteration no $a"
done done

Example

a=0
# -lt is less than operator

#Iterate the loop until a less than 10


while [ $a -lt 10 ]
do
# Print the values
echo $a

# increment the value


a=`expr $a + 1`
done

BREAK – CONTINUE
Break command is used to exit out of current loop completely
before the actual ending of loop. It comes handy when we don’t have prior
knowledge of how long will the loop last like when we user’s input is
required.

Example
#!/bin/bash
#breaking a loop
num=1
while [ $num –lt 10 ]
do
if [ $num –eq 5 ]
then
break
fi
done
echo “Loop is complete”

Continue command is used in script to skip current iteration of loop &


continue to next iteration of the loop.

Example
#!/bin/bash
# using continue command
for i in 1 2 3 4 5 6 7 8 9
do
if [ $i –eq 5 ]
then
echo “skipping number 5”
continue
fi
echo “I is equal to $i”
done

EVALUATING EXPRESSIONS
The expr is a command line Unix utility which evaluates an
expression and outputs the corresponding value. expr evaluates integer or
string expressions, including pattern matching regular expressions. Most of
the challenge posed in writing expressions is preventing the invoking
command line shell from acting on characters intended for expr to process.
The operators available for integers: addition, subtraction, multiplication,
division and modulus for strings: find regular expression, find a set of
characters in a string; in some versions: find substring, length of string for
either: comparison (equal, not equal, less than, etc.)
Options Tag Description
--help Display a help message and exit.
--version Display version information and exit.
Examples:
To perform addition of To increament variable : To perform
two numbers: $ y=10 multiplication
$ expr 3 + 5 $ y=`expr $y + 1` $ expr 5 \* 3
output: 8 $ echo $y output:15
output:11
To find the To find substring of To find length of string
index/position of string: a=hello
character in a string a=hello b=`expr length $a`
a=hello b=`expr substr $a 2 3` echo $b
b=`expr index $a l` echo $b output: 5
echo $b output: ell
output: 3 ( as letter l is
at position 3.)

The bc command is used for command line calculator. It is similar


to basic calculator by using which we can do basic mathematical
calculations. Arithmetic operations are the most basic in any kind of
programming language. Linux or Unix operating system provides the bc
command and expr command for doing arithmetic calculations. We can use
these commands in bash or shell script also for evaluating arithmetic
expressions.

Syntax:
bc [ -hlwsqv ] [long-options] [ file ... ]
Options:
-h, {- -help } : Print the usage and exit
-i, {- -interactive } : Force interactive mode
-l, {- -mathlib } : Define the standard math library
-w, {- -warn } : Give warnings for extensions to POSIX bc
-s, {- -standard } : Process exactly the POSIX bc language
-q, {- -quiet } : Do not print the normal GNU bc welcome
-v, {- -version } : Print the version number and copyright and quit
Examples
Input : $ echo "12+5" | bc Input: Input: $ echo
Output : 17 $ x=`echo "12+5" | bc` "var=10;var" | bc
Input : $ echo "10^2" | bc $ echo $x Output: 10
Output : 100 Output:17
Input: $ echo "10>5" | bc Input: Input: $ echo
Output: 1 $ x=`echo "var=10;++var" | bc
"var=500;var%=7;var" | bc` Output: 11
Input: $ echo "1==2" | bc $ echo $x
Output: 0 Output:3

STRINGS
Finding length of a Finding substring of a Matching number of
string string characters in two
x=geeks strings
x=geeks sub=`expr substr $x 2
len=`expr length $x` 3` $ expr geeks : geek
echo $len echo $sub

GREP
The grep filter searches a file for a particular pattern of characters,
and displays all lines that contain that pattern. The pattern that is searched
in the file is referred to as the regular expression (grep stands for globally
search for regular expression and print out).

Syntax:
grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

Example

 Case insensitive search : The -i option enables to search for a string


case insensitively in the give file. It matches the words like “UNIX”,
“Unix”, “unix”.
$grep -i "UNix" geekfile.txt

 Displaying the count of number of matches : We can find the number


of lines that matches the given string/pattern
$grep -c "unix" geekfile.txt

 Display the file names that matches the pattern : We can just display
the files that contains the given string/pattern.
$grep -l "unix" *
Or $grep -l "unix" f1.txt f2.txt f3.xt f4.txt

 Checking for the whole words in a file : By default, grep matches the
given string/pattern even if it found as a substring in a file. The -w
option to grep makes it match only the whole words.
$ grep -w "unix" geekfile.txt

 Displaying only the matched pattern: By default, grep displays the


entire line which has the matched string. We can make the grep to
display only the matched string by using the -o option.
$ grep -o "unix" geekfile.txt

ARRAYS
An array is a data structure consist multiple elements based on key
pair basis. Each array element is accessible via a key index number. An
Array is a data structure that stores a list (collection) of objects (elements)
that are accessible using zero-based index. In Linux shells, arrays are not
bound to a specific data type; there is no array of data type integer, and
array of data type float. An array can contain an integer value in one
element, and a string value in the element next to it.

Defining Array Values


The difference between an array variable and a scalar variable can
be explained as follows. Suppose we are trying to represent the names of
various students as a set of variables. Each of the individual variables is a
scalar. Here array_name is the name of the array, index is the index of the
item in the array that we want to set, and value is the value we want to set
for that item.
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"

If we are using the bash shell, here is the syntax of array initialization –

array_name=(value1 ... valuen)

Accessing Array Values


#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
Example
# !/bin/bash # !/bin/bash
# To declare static Array # To declare static Array
arr=(1 12 31 4 5) arr=(1 2 3 4 5)
i=0
# Loop upto size of array # loops iterate through a
# starting from index, i=0 # set of values until the
while [ $i -lt ${#arr[@]} ] # list (arr) is exhausted
do for i in "${arr[@]}"
# To print index, ith do
# element # access each element
echo ${arr[$i]} # as $i
echo $i
# Increment the i = i + 1 done
i=`expr $i + 1`
done

You might also like