Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

SHELL PROGRAMMING (DN)

CLASS : II B.Sc IT SUNJECT CODE: 17UIT3A5

UNIT I

TOPIC 1 : STARTING TO LINUX: INTRODUCTION TO LINUX: WHAT IS LINUX?

Linux is the successor of Unix operating system.

Linux was developed by Linus Torvalds at the University of Helsenki in the year 1991.

Linux was developed under Intel 80386 processors and it is monolithic kernel.

Linux is available in all computer systems and almost in all types of processors which include

PC based systems, hand held devices, SunSpark systems, IBM Power PC, Intel Pentium systems.

Most of the codings of Linux is written in C programming and therefore it is very easy to understand.

Linux was released under the GPU/GPU (General Public Licence).

GPU is a series of widely used free software licences that gurarantee the end users the freedom to run

study, share and modify the software.

Therefore Linux is also called open source operating system.


The largest part of the work on Linux is done by the thousands of programmers around the world.

Features:

Portable

Multitasking

Multi user

Multiprocessor

Multi thread

Virtual memory

Hierarchical file system

GUI

Multiple virtual consoles

Dynamically linked and shared libraries and static libraries

Shell

Open source

Strong security
What is a shell?

A shell is a user interface for access to an operating system’s services. Generally a shell uses either

Command Like Interpreter (CLI) or Graphical User Interface (GUI).

Advantages:

i) Open source

ii) security

iii) Revive older computer systems

iv) Software updates

v) Customization

vi) Various distributions

vii) Free of cost

viii) Reliability

ix) Performance

x) privacy
xi) Fast and easy to install

xii) Multi tasking and Multi user OS

i) Open source:

Linux source code is available for everyone. Anyone capable of coding can contribute modify, or add
new codings to it and then distribute it around the world later at any time for any purpose.

ii) Security:

Linux is more secured than Windows OS. Linux is not completely secured but it is less vulnerable
than other OS. Every program in Linux needs an authorization from the administrator in the form of password.
There is no requirement of anti virus softwares in Linux as it has in-built anti virus program.

iii) Revive older systems:

Linux helps to use old or outdated programs like firewalls, back up server etc., in your system.

iv) Software updates:

Linux encounters a large number of software updates. These updates are done faster in Linux than
any other Operating system.

v) Customization:

You can customize any feature, wall paapers, screen settings as it is open source.

vi) Free of cost:

Linux is freely available on the web to use. You do not need any licence also for it as it has GNU.
vii) Reliability:

Linux system rarely slows down or freezes. You can work without any disturbances.

viii) Performance:

Linux provides large number of users to use simultaneously and still provides high performance on
various workstations.

ix) Privacy:

Linux ensures privacy of user’s data.

x) Fast and easy to install:

Linux can be easily installed from the web and can run on any hardware even on oldest systems.

xi) Multi tasking and Multi user OS:

It can perform more than one task simultaneously and it allows more than one user to operate it
simultaneously.

xii) Various distributions:

There are many distributions available on Linux such as Fedora, Ubuntu, Debian, Red Hat, etc.,
TOPIC 2: GNU PROJECT AND THE FREE SOFTWARE FOUNDATION
Linux owes its existence by the cooperative efforts of large number of people.

The OS kernel itself forms a small part of usable system.

Commercial UNIX system traditionally come bundled with applications that provides system services and
tools.

For Linux systems, these additional programs have been written by many different programmers and have
been freely contributed.

Linux community supports the concept of free software, that is software that is free from restrictions, subject
to the GNU (General Phublic Licence).

Although there may be a cost involved inobtaining the software, it can thereafter be used in anyway as
desired, usually distributed in source form.

The free software foundation was set by Richard Stallman.

Stallman is a pioneer of the free software concept and started the GNU project, an attempt to create an OS
and development environment compatible to UNIX, but not suffer the restrictions of the proprietary UNIX source
code.

The GNU project already provided the software community with many applications that closely mimic in
UNIX systems.

You can find a copy of the licence http://www.gnu.org


TOPIC 3 : LINUX DISTRIBUTIONS
Linux is actually a kernel. You can obtain the sources for the kernel to compile and install it on a machine
and then obtain and install many other freely distributed software programs to make a complete Linux installation.

These installations are referred to as Linux systems. These installations can be downloaded from internet.

Some of the distributions are:

a) Red hat

b) Ubuntu

c) Slackware

d) Debian

e) Suse

a) Red Hat:

Red Hat was created by the company Red Hat in the year 1995.

Later, it was discontinued RHEL Red Hat Enterprise Linux edition in the year 2004.

Instead, Fedora was release in collaboration with the company Fedora.

Features:

Red Hat introduced a graphical installer called Anaconda developed by Ketan Bengal, intended to be easy to
use for novices.
It also introduced a toolkit called Lokkit, for configuring the firewall capabilities.

Red Hat lacked many features due to copyright and patents problem.

b) Ubuntu:

Ubuntu is a Linux Distribution based on Debian and composed of free and open source software.

Ubuntu is officially released in four editions such as

-- server -- desktop -- core and -- robots

Ubuntu is popular OS for cloud computing.

Ubuntu was developed by a small team of Debian in the year 2004.

Features:

The desktop version of Ubuntu supports all types of softwares that could run on Windows.

It supports Office Suite and Libre Office.

Ubuntu has an in built email software called ThunderBird, which gives users access to emails.

c) Slackware:

Slackware was released by Patrick Volkerding in the year 1993.

It has twin goals such as easy to use and stability for top priorities.
Features:

Easy to use.

Extensive online documentation.

Menu driven package system.

Provides X windows systems.

d) Debian:

Debian was developed by Richard Stallman (GNU organization started by him) in 1993.

Features:

Debian is now java friendly.

Debian can run some peculiar video formats and extensions. Eg moonlight and moonshine program.

Provides X windows systems.

Renewed emphasis on security.

e) Suse:

Suse was developed by the company Suse in 1998.

"S.u.S.E." (Software und System-Entwicklung "Software and systems development").


Features:

Reliability.

Customized images.

Security.

Freedom of vendor.

TOPIC 4 : PROGRAMMING LINUX


-- Many people think that programming linux means using C.

-- It is true that Unix and Linux was written in C. But C is not the only option available to C programmers.

-- A vast range of programs are available. Many of them are free and available on CD ROM.

-- Some of the programs are as follows:

* Ada

* C

* C++

* Eiffel

* Fourth

* Fortran
* Icon

* Java

* JavaScript

* Lisp

* Modula2

* Modula3

* Oberon

* Objective C

* Pascal

* Perl

* PostScript

* Prolog

* Python

* Ruby

* Small Talk

* PHP
* TCL

* BourneShell

TOPIC 5 : LINUX PROGRAMS


-- Linux applications are represented by two types of files, they are

executable files and

scripts

-- Executable files are programs that can be run directly by the computer. They correspond to windows .exe files.

-- Scripts are collections of instructions for another program. These correspond to windows .bat or .cmd files or

interpreted BASIC programs.

-- Linux does’nt require executable or scripts to have a specific filname or any extension whatsoever.

-- When logged into Linux, the user can interact with a shell program (bash) that runs programs in the same way

that the windows command prompt does. C:/>cd sample C:/sample>cd.. $ gedit sample.c

-- It the programs that the user asks by its name given in the directories.

-- The directories to store are stored in a shell variable PATH like windows.

-- The search path is configured by the system administrator and it contains as follows:
/bin – binaries, programs used in booting the system

/usr/bin -- user binaries, standard programs available to users

/usr/local/bin – local binaries, programs specific to installation

-- An administrator login such as a root may use a PATH variable that includes the directories where the system

administration programs are kept such as /sbin or /usr/sbin.

-- Optional OS components and third party applications may be installed in sub directories of /opt.

-- Linux uses colon (colon) to separate entries in the PATH variable rather than the semicolon (;) used in

MS DOS.

-- Eg. PATH variable /usr/local/bin:/usr/bin:.:/home/neil/bin:/usr/X11R6/bin

TOPIC 6 : TEXT EDITORS


-- To write a program in Linux, we need an editor window. There are many to choose but vi editor is most

popular one. gedit ubuntu

-- Emacs is also one familiar editor window used for graphical applications.

-- Almost all Linux distributions have inbuilt Emacs packages.

-- Emacs has its entire manual available.

-- To do this, start the editor, run the Emacs and then type Ctrl + H followed by t for tutorial and Ctrl + H, i
for information.

TOPIC 7 : C COMPILER
-- On POSIX operating system, C compiler is called c89.

-- Historically, C compiler is called as cc.

-- Over the years, different vendors have sold UNIX like operating systems with C compiler, but still it is called as

cc.

-- However, on Linux operating system, the term cc, c89, gcc , all refers to C compiler. Usually here we call the C

compiler as gcc because of GNU C Compiler.

-- In Unix operating system, the C compiler is called as cc.

Eg: C program:

#include<stdio.h>

#include<stdlib.h>

int main()

printf(“HELLO WORLD \n”);

return 0;
}

To save:

sample.c

To compile:

$ gcc sample sample.c

To run:

$ ./sample

-- On executing this program, the C compiler cc will translate the source code into an executable code and

produces output.

TOPIC 8 : SHELL PROGRAMMING : WHAT IS SHELL

-- Shell: A shell is a program that act as the interface between the user and the Linux OS, enabling the user to enter

commands for the operating system to execute.

-- Linux shells are much more powerful than the Windows command prompt.

-- For example, input or output can be redirected using < and >

data piped between simultaneously executing programs using |

output from a sub process can be grabbed using $ (…)


other programs

X windows
bash
kernel

csh

-- The above diagram shows how the Linux (bash, csh) and other programs sits around the kernel.

-- A Shell provides you with an interface to the Unix system. It gathers input from you and executes programs based on
that input. When a program finishes executing, it displays that program's output.
Shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of a
shell, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized
commands and functions.

Shell Prompt
-- The prompt, $, which is called the command prompt, is issued by the shell. While
the prompt is displayed, you can type a command.
-- Shell reads your input after you press Enter. It determines the command you want
executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words.
Following is a simple example of the date command, which displays the current date
and time −
$date
Thu Jun 25 08:30:19 MST 2009
Types of Linux Shells:
i) Bourne-Again Shell
-- Bash stands for Bourne Again Shell and it is the default shell on many Linux
distributions today. It is also a sh-compatible shell and offers practical improvements
over sh for programming and interactive use which includes:
 Command line editing

 Job Control

 Unlimited size command history


ii) TENEX C Shell
-- Tcsh is enhanced C shell, it can be used as an interactive login shell and shell script
command processor.
Tcsh has the following features:
 C like syntax

 Command-line editor

 Programmable word and filename completion

 Spelling correction

 Job control

-- Ksh stands for Korn shell and was designed and developed by David G. Korn. It is a
complete, powerful, high-level programming language and also an interactive command
language just like many other Unix/GNU Linux shells.

iii) Korn shell:


-- The Korn shell includes features from other shells and provides several more
advanced features found in modern scripting languages such as;

 associative arrays
 floating point arithmetic

 job control

iv) Z Shell
-- Zsh is designed to be interactive and it incorporates many features of other Unix/GNU
Linux shells such as bash, tcsh, and ksh.
-- It is also a powerful scripting language just like the other shells available. Though it
has some unique features that include:
 Filename generation

 Startup files

 Login/Logout watching

 Closing comments

 Scheme Shell

 The Scheme shell (scsh) is an exotic shell that offers a scripting environment

using Scheme, which is a derivative of the Lisp language. The Pyshell is an attempt
to create a similar script that uses the Python language.

v) Scheme Shell
-- The Scheme shell (scsh) is an exotic shell that offers a scripting environment using Scheme,
which is a derivative of the Lisp language. The Pyshell is an attempt to create a similar script that
uses the Python language.
TOPIC 9 : # PIPES AND REDIRECTIONS #
-- Before we get down to the details of shell programs, we need to say a little about how
inputs and outputs of Linux programs (not just shell programs) can be redirected.
i) redirecting output
ii) redirecting input
iii) pipes
Redirecting Output:
-- You may already be familiar with some redirection, such as
$ ls -l > sample.txt
ls command list out the various directories or files.
ls -1 saves the output of the ls command into a file called sample.txt.
-- File descriptor 0 is the standard input to a program, file descriptor 1 is the standard
output, and file descriptor 2 is the standard error output.
-- The preceding example redirects the standard output into a file by using the >
operator. By default, if the file already exists, then it will be overwritten.
-- If you want to change the default behavior, you can use the command set -o noclobber
(or set -C), which sets the noclobber option to prevent a file from being overwritten.
Eg.
$ ps >> sample.txt
ps displays the process’s status.
≫ will append the output of the ps command to the sample file.
The command
$ kill -HUP 1234 >killout.txt 2>killerr.txt
will put the output and error information into separate files.
-- If you prefer to capture both sets of output into a single file, you can use the >&
operator to combine the two outputs. Therefore,
$ kill -1 1234 >killouterr.txt 2>&1
will put both the output and error outputs into the same file. Notice the order of the
operators. This reads as “redirect standard output to the file killouterr.txt, and then direct
standard error to the same place as the standard output.” If you get the order wrong, the
redirect won’t work as you expect.
$ kill -1 1234 >/dev/null 2>&1
Redirecting Input
Rather like redirecting output, you can also redirect input. For example,
$ more < killout.txt
-- Obviously, this is a rather trivial example under Linux; the Linux more command is
quite happy to accept filenames as parameters, unlike the Windows command-line
equivalent.

Pipes
-- Pipe is used to combine two or more commands, and in this, the output of one
command acts as input to another command, and this command’s output may act as input
to the next command and so on.
-- You can connect processes using the pipe operator ( | ). In Linux, unlike in MS-DOS,
processes connected by pipes can run simultaneously and are automatically rescheduled
as data flows between them. As a simple example, you could use the sort command to
sort the output from ps.
-- If you don’t use pipes, you must use several steps, like this:
$ ps > psout.txt
$ sort psout.txt > pssort.out
-- A much more elegant solution is to connect the processes with a pipe:
$ ps | sort > pssort.out
-- Because you probably want to see the output paginated on the screen, you could
connect a third process, more, all on the same command line:
$ ps | sort | more
$ ps | sort | uniq | grep -v sh | more
This takes the output of ps, sorts it into alphabetical order, extracts processes using uniq,
uses grep -v sh to remove the process named sh, and finally displays it paginated on the
screen.
cat mydata.txt | sort | uniq | grep –v > mydata.txt
you will end up with an empty file, because you will overwrite the mydata.txt file before
you read it.
TOPIC 10 : THE SHELL AS A PROGRAMMING LANGUAGE
i) interactive program
ii) creating a script
iii) making a script executable
-- There are two ways of writing shell programs. $ ls mydata.txt
cat mydata.txt smk.txt > a.txt
grep –v sh

-- You can type a sequence of commands and allow the shell to execute them
interactively, or you can store those commands in a file that you can then invoke as a
program.
i) Interactive Programs
-- Just typing the shell script on the command line is a quick and easy way of trying out
small code fragments.
-- You are almost certainly aware of the use of ‘*‘ as a wildcard to match a string of
characters.
[^set] negates the set — that is, it includes anything but the set you’ve specified.
-- Brace expansion using {} (available on some shells, including bash) allows you to
group arbitrary strings together in a set that the shell will expand. For example,
$ ls my_{finger,toe}s
$ ls my_finger, my_toes

will list the files my_fingers and my_toes. This command uses the shell to check every
file in the current directory.
ii) Creating a Script
-- Using any text editor, you need to create a file containing the commands; create a file
called first that looks like this:
#!/bin/sh
# first #
-- This file looks through all the files in the current # directory for the string POSIX, and
then prints the names of # those files to the standard output.
for file in * do if grep -q POSIX $file then echo $file fi done
exit 0
-- Comments start with a # and continue to the end of a line.
-- Conventionally, though, # is kept in the first column. Having made such a sweeping
statement, we next note that the first line, #!/bin/sh, is a special form of comment;
-- The #! characters tell the system that the argument that follows on the line is the
program to be used to execute this file. In this case, /bin/sh is the default shell program.
-- It is conventional to keep this shorter than 32 characters, because some older UNIX
versions can only use this limited number of characters when using #!, although Linux
generally does not have this limitation.
-- A zero denotes success in shell programming. Since the script as it stands can’t detect
any failures, it always returns success.
iii) Making a Script Executable
-- Now that you have your script file, you can run it in two ways. The simpler way is to
invoke the shell with the name of the script file as a parameter:
$ /bin/sh first
-- Change Mode for permissions:
$ chmod +x first
-- To change this, either type PATH=$PATH:.
Then log out and log back in again. Alternatively: type
./first
in the directory containing the script, to give the shell the full relative path to the file.
-- To prevent other users from changing the script, perhaps accidentally, you should
remove write access from it.
-- To give all access rights to a file : we can use the following command :chmod 777
/usr/local/bin/first
Eg.
# chmod u=rwx, go=rx /usr/local/bin/first
There are three Classes – Owner, Group, Others.
 The Owner is the usually the creator of the files/folders. In Linux, files or folders
that you created in your Home directory are usually owned by you, unless you
specifically change the ownership.

 The Group contains a group of users who share the same permissions and user
privilege.

 Others means the general public.

Various access permissions:

0–no permission
1 – execute
2 – write
3 – write and execute
4 – read
5 – read and execute
6 – read and write
7 – read, write, and execute

TOPIC 11 : SHELL SYNTAX


-- The shell is quite an easy programming language to learn, not least because it’s easy to
test small program fragments interactively before combining them into bigger scripts.
-- You can use the bash shell to write quite large, structured programs.
-- Some of the important keywords and its syntax.
❑ Variables: strings, numbers, environments, and parameters
❑ Conditions: shell Booleans
❑ Program control: if, elif, for, while, until, case
❑ Functions
❑ Commands built into the shell
Variables
-- There is no need to declare variables in the shell before using them.
int a;
a=10;
a=10; b=20
a=”fgdg”
a+b 1020

-- Instead, create them by simply using them (for example, when you assign an initial
value to them). a=7 $echo $a
-- By default, all variables are considered and stored as strings, even when they are
assigned numeric values.
-- The shell and some utilities will convert numeric strings to their values in order to
operate on them as required.
-- Within the shell can access the contents of a variable by preceding its name with a $.
-- Whenever you extract the contents of a variable, you must give the variable a
preceding $.
Eg.
$ salutation=Hello
$ echo $salutation
output : Hello

$ salutation=”Yes Dear”
$ echo $salutation
output: Yes Dear

$ salutation=”7+5”
$ echo $salutation
output: 7+5
-- A string must be delimited by quote marks if it contains spaces. In addition, there can’t
be any spaces on either side of the equals sign.
-- User inputs to a variable can be assigned by using the read command.
-- This takes one parameter, the name of the variable to be read into, and then waits for
the user to enter some text. The read normally completes when the user presses Enter.
When reading a variable from the terminal, you don’t usually need the quote marks:
Eg:
$ echo “Enter the value for a”
$ read salutation
input: Where are you going?
$ echo $salutation
output: Where are you going?

Eg.
$ read a input : Hello How are you
$ echo $a output: hello how are you
-- Quoting Before moving on, you should be clear about one feature of the shell: the use
of quotes.
-- The parameters in scripts are separated by whitespace characters (e.g., a space, a tab,
or a newline character). If a parameter has to contain one or more whitespace characters,
must quote the parameter.
-- If it is enclosed in single quotes, then no substitution takes place.
-- Can also remove the special meaning of the $ symbol by prefacing it with a \.
-- Usually, strings are enclosed in double quotes, which protects variables from being
separated by white space but allows $ expansion to take place.
Eg.
myvar=”Hi there”
echo $myvar
echo “$myvar”
echo ‘$myvar’
echo \$myvar
echo Enter some text
read myvar
echo ‘$myvar’ now equals $myvar exit 0
This behaves as follows(outputs)
$ ./variable Hi there
Hi there
$myvar
$myvar

Enter some text


Hello World
$myvar now equals Hello World
Environment Variables
-- When a shell script starts, some variables are initialized from values in the
environment.
-- These are normally in all uppercase form to distinguish them from user-defined (shell)
variables in scripts, which are conventionally lowercase.
Environment Variable Description
-- $HOME The home directory of the current user
-- $PATH A colon-separated list of directories to search for commands
-- $$ The process ID of the shell script, often used inside a script for generating unique
temporary filenames; for example /tmp/tmpfile_$$

Conditions
-- Fundamental to all programming languages is the ability to test conditions and
perform different actions based on those decisions.
-- A shell script can test the exit code of any command that can be invoked from the
command line, including the scripts that you have written yourself.
-- That’s why it’s important to always include an exit command with a value at the end
of any scripts that you write.
if test -f fred.c then ... fi
You can also write it like this:
if [ -f fred.c ] then ... fi
-- The test command’s exit code (whether the condition is satisfied) determines whether
the conditional code is run.
-- Test command fall into three types: string comparison, arithmetic comparison, and file
conditionals. The following table describes these condition types:
-- If you prefer putting then on the same line as if, you must add a semicolon to separate
the test from the then:
if [ -f fred.c ]; then ... fi
String Comparison Result
string1 = string2 True if the strings are equal
string1 != string2 True if the strings are not equal
-n string True if the string is not null
-z string True if the string is null (an empty string)
Arithmetic Comparison Result
expression1 -eq expression2 True if the expressions are equal
expression1 -ne expression2 True if the expressions are not equal
expression1 -gt expression2 True if expression1 is greater than expression2
expression1 -ge expression2 True if expression1 is greater than or equal to expression2
expression1 -lt expression2 True if expression1 is less than expression2
expression1 -le expression2 True if expression1 is less than or equal to expression2
! expression True if the expression is false, and vice versa
File Conditional Result
-d file True if the file is a directory
-e file True if the file exists. The -e option has not been portable, so -f is usually used.
-f file True if the file is a regular file
-g file True if set-group-id is set on file
-r file True if the file is readable
-s file True if the file has nonzero size
-u file True if set-user-id is set on file
-w file True if the file is writable
-x file True if the file is executable
Control Structures
The shell has a set of control structures, which are very similar to other programming
languages.
if -- The if statement is very simple: It tests the result of a command and then
conditionally executes a group of statements:
if condition then statements
else statements fi
-- A common use for if is to ask a question and then make a decision based on theanswer
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]; then echo timeofday “Good morning”
else echo timeofday “Good afternoon”
fi exit 0
Output:
Is it morning? Please answer yes or no yes Good morning $

-- Replacing the else with elif and then adding another condition:
#!/bin/sh
echo “Is it morning? Please answer yes or no” read timeofday
if [ $timeofday = “yes” ] then echo “Good mo
elif [ $timeofday = “no” ]; then echo “Good afternoon”
else echo “Sorry, $timeofday not recognized. Enter yes or no” exit 1
fi
exit 0
[: =: unary operator expected
if [ = “yes” ]
which isn’t a valid condition.
An empty variable then gives the valid test:
if [ “” = “yes” ]
Eg.
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ “$timeofday” = “yes” ] then echo “Good morning”
elif [ “$timeofday” = “no” ]; then echo “Good afternoon”
else echo “Sorry, $timeofday not recognized. Enter yes or no”
exit 1
fi exit 0
echo -n -- -n option with echo statement is used to feed a new line.
for condition: used to execute a set of statements repeatedly.
for file in $(condition);
do
lpr $file
done
exit 0
while condition: used to execute a set of statements until some condition is true.
while condition do statements done
For example, here is a rather poor password-checking program:
#!/bin/sh
echo “Enter password”
read trythis
while [ “$trythis” != “secret” ];
do
echo “Sorry, try again”
read trythis
done
exit 0
output:
Enter password jamal
Sorry, try again $
until executes a set of statements until the condition is false.
until condition
do
statements
done
Eg.
#!/bin/bash
until who | grep “$1” > /dev/null do sleep 60 done
# now ring the bell and announce the expected user.
echo -e ‘\a’ echo “**** $1 has just logged in ****“
exit 0
If the user is already logged on, the loop doesn’t need to execute at all, so using until is a
more natural choice than while.
case: executes a particular case when it matches with the case.
case variable in pattern [ | pattern] ...) statements;; pattern [ | pattern] ...) statements;; ...
esac
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
case “$timeofday” in yes) echo “Good Morning”;; no ) echo “Good Afternoon”;;
y ) echo “Good Morning”;; n ) echo “Good Afternoon”;; *) echo “Sorry, answer
not recognized”;;
esac
exit 0
The preceding case construction is clearly more elegant than the multiple if statement
version, but by putting the patterns together, you can make a much cleaner version:
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
case “$timeofday” in yes | y | Yes | YES ) echo “Good Morning”;;
n* | N* ) echo “Good Afternoon”;;
*) echo “Sorry, answer not recognized”;;
esac
exit 0
The AND List
-- The AND list construct enables you to execute a series of commands, executing the
next command only if all the previous commands have succeeded. The syntax is
statement1 && statement2 && statement3 && ...
The OR List
-- The OR list construct enables us to execute a series of commands until one succeeds,
and then not execute any more. The syntax is as follows:
statement1 || statement2 || statement3 || ...
#!/bin/sh
rm -f file_one
if [ -f file_one ] || echo “hello” || echo “ there” then echo “in if” else echo “in else” fi
exit 0
This results in the following output:
hello in if
Functions
-- User defined functions are used to accomplish some tasks which the user allots, and it
can be called wherever necessary.
function_name () { statements }
#!/bin/sh
foo()
{
echo “Function foo is executing”
}
echo “script starting” foo
echo “script ended”
exit 0

output:
script starting Function foo is executing script ended

#!/bin/sh
sampletext=” This is global variable”
foo() {
local sampletext=”This is local variable”
echo “Function foo is executing”
echo $sampletext
}
echo “Hello world”
echo $sampletext
output:

Function foo is executing


This is local variable
Hello world
This is global variable

Commands
-- Two types of commands from inside a shell script. There are “normal” commands that
you could also execute from the command prompt (called external commands), and there
are “built-in” commands (called internal commands).
eval The eval command enables you to evaluate arguments. It’s built into the shell and
doesn’t normally exist as a separate command.
foo=10
x=foo
y=’$’$x
echo $y
This gives the output $foo. However,
foo=10
x=foo
eval y=’$’$x
echo $y
gives the output 10.
exec The exec command has two different uses. Its typical use is to replace the current
shell with a different program. For example,
exec wall “Thanks for all the fish”
in a script will replace the current shell with the wall command. No lines in the script
after the exec will be processed, because the shell that was executing the script no longer
exists.
Exit Code Description
126 The file was not executable
127 A command was not found
expr The expr command evaluates its arguments as an expression. It’s most commonly
used for simple arithmetic in the following form:
x=`expr $x + 1`

Expression Evaluation Description


expr1 | expr2 expr1 if expr1 is nonzero, otherwise expr2
expr1 & expr2 Zero if either expression is zero, otherwise expr1
expr1 = expr2 Equal
expr1 > expr2 Greater than
expr1 >= expr2 Greater than or equal to
expr1 < expr2 Less than
expr1 <= expr2 Less than or equal to
expr1 != expr2 Not equal
expr1 + expr2 Addition
expr1 - expr2 Subtraction
expr1 * expr2 Multiplication
expr1 / expr2 Integer division
expr1 % expr2 Integer modulo
Escape Sequence Description
\“ Double quote
\\ Backslash character
\a Alert (ring the bell or beep)
\b Backspace character
\c Suppress further output
\f Form feed character
\n Newline character
\r Carriage return
\t Tab character
\v Vertical tab character
\ooo The single character with octal value ooo
\xHH The single character with the hexadecimal value HH
set The set command sets the parameter variables for the shell. #!/bin/sh
echo the date is $(date) set $(date)
echo The month is $2
exit 0
shift The shift command moves all the parameter variables down by one, so that $2
becomes $1, $3 becomes $2, and so on.

Signal Description
HUP (1) Hang up; usually sent when a terminal goes offline, or a user logs out
QUIT (3) Quit; usually sent by pressing Ctrl+\
ABRT (6) Abort; usually sent on some serious execution error
ALRM (14) Alarm; usually used for handling timeouts
TERM (15) Terminate; usually sent by the system when it’s shutting down

The find Command


This is used to search for files
The grep Command General Regular Expression
The find command is to search the system for files, but grep command is to search files
for strings.

You might also like