Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

AMITY INSTITUTE OF INFORMATION

TECHNOLOGY

Module –6
Shell introduction and Shell Scripting:


Learning Objectives
•Imparting UNIX programming skill to students

•Knowledge of Shell Programming in context of


UNIX OS

•Designing applications using latest UNIX Shell


Programming Scripts
Contents to be Covered
• Introduction to OS
• Functions of OS
• Classification of Operating systems
• Interface of UNIX
• History of UNIX
• Features of UNIX
INTRODUCTION

• An operating System (OS) is a set of programs that manages


computer hardware and software resources and provides
common services for computer Programs. Example: UNIX ,
Windows, DOS.

• It acts as an interface between user and hardware of the


computer system. Without an operating system, no software
programs can run.

• The OS is what allocates memory, processes tasks, accesses


disks and peripherals, and serves as the user interface
Operating System
Functions of operating system
An operating system is expected to perform various
functions. These functions can be broadly categorized as:
• Command Interpretation
• Peripheral Management
• Memory Management
• Process Management
• Storage Management
• File-System Management
• Protection and Security
• Resource Management
Types of Operating System
• Single-User Systems

• Multi-User Systems

Single-User Systems

DOS is an example of single-user OS.A personal computer (PC) is a popular single-user


system. The personal computer was designed for use by one person at a time, since it is
single-user oriented with MS-DOS OS

Multi-user Systems

Multi-user Systems are used by more than one person at a time. Multi-user Systems are
required when a number of programs have to be run simultaneously, or common resources like
printers and disks are to be shared by number of users . A multi-user system consists of a
single computer with several terminals attached to it. This computer can be a PC-AT ,a mini or
a mainframe.
Interface of
Unix OS
• GUI(Graphical User Interface)

LINUX,WINDOWS

• CUI(Command User Interface)

MS-DOS,UNIX
The traditional Unix user interface is a simple command-line shell.

1) The shell prints a prompt when it is ready to receive commands. You use
the keyboard to type in a command. Then the shell parses and processes
the command and executes it for you. The command prints its output, if
any, to the same terminal window. When the command is done, the shell
prompts you again to enter another command terminal window has no
graphics capability

2) There is a GUI shell available for Unix systems, called X Window or


simply X.

This GUI has all the same features that you would find on a personal
computer. In fact, the version used most commonly on modern Unix
systems look very much like Microsoft Windows.
History of UNIX
• UNIX has been a popular OS for more than two decades because of its multi-
user, multi-tasking environment, stability, portability and powerful networking
capabilities.

• UNIX is an operating system which was first developed in the 1960s, and has
been under constant development ever since.

• Ken Thompson then teamed up with Dennis Ritchie, the author of the first C
compiler in 1973. They rewrote the UNIX kernel in C - this was a big step forwards
in terms of the system's portability - and released the Fifth Edition of UNIX to
universities in 1974.

• First operating system written in High Level Language C by Ken Thompson and
Dennis Ritchie
What is UNIX?
• The UNIX operating system is a set of programs that act as a link between
the computer and the user.

• The computer programs that allocate the system resources and coordinate all
the details of the computer's internals is called the operating system or kernel.

• Users communicates 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 was originally developed in 1969 by a group of AT&T employees at Bell


Labs, including Ken Thompson, Dennis Ritchie
Features of UNIX
• Multi-user/Multitasking/timesharing concept
• Portability
• Machine Independence
• Popularity
• Hierarchical File System
• Pipes and Filters
• Unix Shell
• Background Processing
• Multi-user operation
• Security
ARCHITECTURE OF UNIX OS
SHELL AS A COMMAND INTERPRETER
• Shell is an intermediary program which interprets the commnads
that are types at the terminal and translates them into commands
that kernel understands

• Shell acts as a blanket around the kernel and eliminates the need
for the programmer to communicate directly with the kernel

• Shell can be considered as a master utility program which enables a


user to gain access to all other utilities and resources of the
computer.
UNIX FILE SYSTEM
• UNIX file system resemble upside down tree.

• File system begins with a directory called root

• The root directory is denoted by (/)

• Branching from the root there are several other directories called
bin lib,usr,etc,temp,dev

• The root directory also contain a file called UNIX which is UNIX
kernel itself.

• These directories are called sub directories ,their parent being the
root directory
Cont…
bin Binary Executable File contain files for most of the UNIX command and commands can be
either C programs or shell programs

lib Directory contains all the library functions provided by the UNIX for programmers. The
programs written under UNIX make use of these library functions in the lib directory.
dev Device related files that controls various input/output devices like terminals, printers etc

etc Contains binary executable files required for System administration


tmp Temporary files created by the UNIX or users. All temporary files. UNIX can afford to
dispense these files. These files automatically get deleted when system shutdown or
restarted

Usr Home directory of all users. In this there are several directoris,each associated with a
particular user. Each user is allowed to work in his own directory

/usr/bin Additional binary executable files. Within the user there is another bin directory which
contains additional UNIX commands files
Creating a directory
• The mkdir(make directory)command is used to create directories
• $ mkdir project
• The subdirectory project is created under the current directory.
• $ mkdir / user/games/project
Removing a directory
• The rmdir(remove directory)removes the directory specified.
• $ rmdir cobol
•$
• where cobol is the directory which is deleted.
• A directory can be deleted only if it is :
• Empty
• Not the current directory.
Managing Directories
rmdir: Remove directory

rmdir() attempts to remove the empty directory with the specified name
‘rmdir’ command is used to remove single or multiple directories/sub-directories
under the existing directory with the specified path.

The option/parameter ‘-p’ is used to create directory along with sub-directories

Syntax $rmdir

$rmdir Edu edu


$rmdir /dev/a.txt b.bin c.so
$rmdir -p dir1/dir2/dir
Managing Directories
ls: Listing files and Directories

“ls” command is used to display the list of files and directories in ascending order

The options used with ls


Syntax $ls

$ls –t last edited/modified files and dir in ascending order


$ls –r display files with descending or reverse order
$ls –R list of files ,directories and sub-directories recursively in tree structure
$ls –c or –x display in multi columnar output or width wise
$ls –X display alphabetically/ascending order by entry extension
$ls –a List the entries or files along with hidden files begins with .(dot)

Other options: -v,-I,-u * -l –A etc


File Creation
touch

• If the file exists ,it will update the time stamp


• If the file does not exist,it creates a new empty file with 0 KB file size
• We cannot insert any content into the file by using the “touch” command

Advantage of “touch” command:


• Multiple files can be created in a single command line

• $ touch filename
Example:
• touch x.txt y.so z.xl
• touch 03161430 z.xl
• touch file{1,2,3,4}
Create ,Display and Delete Files
• If File is already existing,it will not create a new file with the same name
under that directory
• If the file does not exist,then it creates a new file in write mode where we can
insert any content
• Ctrl+d keywords is used to come out of the file after placing the content

• Disadvantage of “cat” command allows a single file to be created at a time


Hence,multiple files cannot be created at once in a single command line.

$cat>filename

cat>hello
Create ,Display and Delete Files
File creation: vi

If the file already exists, it will open in edit mode


If the file does not exist, it creates a new file in write/edit mode where we can
insert/modify any content
The keyword “Esc :wq” :q! is used to come out of the file after placing the
content
Advantage of “vi” command: It allows to create single/multiple file(s) at a time
in a single command line with read/wite edit mode

Syntax: vi filename
vi aa.sh
vi file1 file2
Create ,Display and Delete Files
File content display:

Following commands are used to display the contents of the file:

$cat,$ vi,$more $less

Cat This command is used to display the content of File(s) and concatenate
the contents

Also used to copy the contents of a file to another file

• Copy: $cat file1>file2


• Display: $cat file1 file 2
• Create $cat >file1
• Append: $ cat file1>> file2
Create ,Display and Delete Files
File content display
more
• For viewing long files , we use the “more “ command
• When the “Space bar” is pressed ,the next screen of information will be
displayed
• Use “q” to quit viewing of files

• $more filename
less
• “less” command is similar to “more” command .It allows backward as well as
forward movement in the file with almost “vi” editor commands features
• “less” command does not have to read the entire input file before starting ,so
with large input files it starts up faster than text editor like “vi”

• less filename
Create ,Display and Delete Files
rm: Delete Files

This command deletes/removes one or more files


Syntax: $ rm filename

Example:
rm f1 f2 f3
rm –rf prog/f5 prog/f6
rm I dir l/ch[12]
rm*

-r recursively deletes the entire contents of directories and sub-directories


-i interactive deletion
-f whenever the current file is being used by any prog and to delete it forcefully
BASIC COMMANDS
PATH - The PATH environment variable is a colon-delimited list of directories that your
shell searches through when you enter a command.
◆ Example: echo $PATH

man - allows users to view the reference manuals of a command or utility run in the
terminal.
◆ Syntax : man [option] [section number] [command name]
◆ Example : man 3 sleep

echo - used for displaying lines of text or string which are passed as arguments on the
command line.
◆ Syntax : echo [option] [string]
◆ Example : $ echo "Welcome to Linux”
printf - used to display the given string, number or any other format specifier on the
terminal window.
◆ Syntax : printf [-v var] format [arguments]
◆ Example : $printf "%s\n" "Hello, World!“

script - used to make typescript or record all the terminal activities.


◆ Syntax : script [options] [file]
◆ Example : $ script file.txt

passwd - used to change the user account passwords.


◆ Syntax : passwd [options] [username]
◆ Example : $ passwd user1

uname - print Unix system information /used to change the user account passwords.
◆ Syntax : uname [OPTION]
◆ Example : $ uname –n

• hostname – show or set server hostname


• w – display system load, who’s logged in and what they are doing
mkdir - allows users to create or make new directories
◆ Syntax : mkdir [options...] [directories ...]
◆ Example : $ mkdir New_Folder
➔ rmdir - remove empty directories from the filesystem in
linux.
◆ Syntax : rmdir [OPTION]... DIRECTORY
◆ Example : $ rmdir New_Folder
➔ cp - used to change the user account passwords.
◆ Syntax : uname [OPTION]
◆ Example : $ uname -n
➔ mv - used to move one or more files or directories from one place to another.
◆ Syntax : mv [options] source destination
◆ Example : $ mv a.txt b.txt

➔ ls - List information about the FILEs (the current directory by default).


◆ Syntax : ls [OPTION]... [FILE]
◆ Example : $ ls

➔ cat - reads data from the file and gives their content as output.
◆ Syntax : cat [OPTION]... [FILE]
◆ Example : $ cat filename.txt

➔ grep - The grep filter searches a file for a particular pattern of characters,
and displays all lines that contain that pattern.
◆ Syntax : grep [options] pattern [files]
◆ Example : $ grep -l "unix" f1.txt f2.txt f3.xt f4.txt
Cont..
• who: tells you who's logged on, and where they're coming from.
• whoami --- returns your username.
• passwd --- lets you change your password.
 date --- shows the current date and time.
 Formatting options of date:
Date +%A---date “+DATE: %A”
Date +%a
Date +%B Month in capital form
Date +%b
Date +%F
date +%T
date +%y
date +%Y
To set Date
• date “+DATE: %m%d%y%n TIME: %H%M%S”
Shell scripts
• A shell script is a text file with Unix commands in it.

• A script is a set of commands, either in a file, or typed in at the


command line, that perform multiple operations on a file or files.
Another term for scripts that might be familiar to you is a ``macro''.
Executing a Shell Script
• To run a file as a script, the file must have the execution bit set., this
means the file looks like this when you look at it:
• $ ls -l
• -rwxr-xr-x 1 joeuser 123 Jun 22 16:05 script.file
The echo command

• The echo command is used to display messages on the screen


• $ echo Hello World
• Hello World
• $ echo "Who's there?"
• Who's there?
Variables

Variables in shell scripts do not have associated data types that is, they
are not declared to be integers or characters. All variables in UNIX are
treated as character strings. It is possible, however, to mathematically
manipulate variables.
Referencing Variables
• The $ symbol is used to refer to the contents of a variable.
• For example, to assign the value of one variable to another, the
command would be:

• variable1=${variable2}
In case no concatenation is involved, the braces are optional

• x=$today
• is the same as
• x=${today}
Reading a value into a variable

• Besides assigning a value to a variable, the shell also allows a user to


enter a value into a variable during execution of a shell script. This is
done using the

• read command.
read var1 var2 var3
this is to test the read
$ echo $var1
this
$ echo $var2
is
$ echo $var3
to test the read
$
The expr Command

• The shell does not support numeric variables.All variables are treated
as
• character strings.Therefore,the declaration
• var1=25
• The use of the expr command is illustrated in the following code:
• A=10
• B=5
• A=’expr’$a-7
• echo “a is equal to $a”
• a=’expr’$a \ *$b’
• echo “a s equal to $a”
• a=’expr’ $a / 3
• echo “a is equal to $a”
• The output of this code would be
• a is equal to 3
• a is equal to 15
• a is equal to 5
Control statements
• Control statements control the flow of execution in a programming
language.

• Without control statements, execution within a shell scripts flows


from one statement to the next in succession.
for loop
• for loops allow the repetition of a command for a specific set of
values.
• Syntax:
for var in value1 value2 ...
do
command_set
done
• command_set is executed with each value of var (value1, value2, ...) in
sequence
Examples

for i in 1 2 3 4 5
do
sum=`expr $sum + $i`
done
echo $sum
Cont…
for name in Ruby Samuel
do

echo “${name}”

done
The UNIX shell offers constructs for looping and decision-
making that can be used in shell scripts. An example is the if…
then…else construct. The if construct is generally used in
conjunction with the test command.

Echo “enter number of the years worked”


Read Years WKd
If test ${YearsWKd}-gt 10
Then echo “Senior”
Else echo “Junior”
fi
• UNIX also provides the if…elif construct,the format of
which is as follows
• If condition(s)
• Then command(s)
• elif condition
• then command(s)
• else commad(s)
• fi
The if command
• Simple form:
if decision_command_1
then
command_set_1
fi
Using elif with if
#! /bin/bash
if grep "UNIX" myfile >/dev/null
then
echo UNIX occurs in myfile
elif grep “DOS” myfile > /dev/null
then
echo DOS appears in myfile not UNIX
else
echo nobody is here in myfile
fi
The case….esac Construct

• This construct is used in shell scripts to perform a specific set of instuctions


depending on the value of a variable and is often used in place of the if construct.
• The case…esac onstruct evalueates the value of the variable and compares it with
each value specified.
• When the value of the variable matches one of the values specified,the set of
command(s) specified under that value is executed.
• The last command to be executed for any value of the variable must be followed
by a pair of semi-colons to delimit it from the set of commands for the next value.
• Syntax:
case string in
pattern1)
command_set_1
;;
pattern2)
command_set_2
;;

esac
#!/bin/bash
echo -n 'Choose option [1-2] > '
read reply
case $reply in
"1")
echo “the choice was 1”
;;
"2")
echo “the choice was 2”
;;
*) Provide a default case when no
echo Illegal choice! other cases are matched.
;;
esac
The while loop
• One of the constructs used to support iteration(looping)in shell scripts
is the while
• construct. The format of this construct is:
• while<condition>
• do
• <command's)>
• done
• Here, the commands within do and done get executed as long as the
condition is
• true.
Program to print 1 to n
n=1
while [ $n –le 10 ]
do
echo $n
n=$(( n+1))
done

or

n=1
while [ $n –le 10 ]
do
echo $n
n=`expr $n +1`
done
How to read files using while loop
while read p //Here p is the variable where we want to save the content line by line
do
echo $p
done< hello.sh //use angle bracket of < input redirection operator it will read hello.sh

Or

// Read the file in a single variable and then print it if u know pipes it would be easier

cat hello.sh |while read p


do
echo $p
done
Example

a=1
while [ $a -le 5 ]
do
echo “value of a=” $a
a=`expr $a + 1`
done
THANK YOU

You might also like