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

Unit III Shell Scripting

Uploaded by

Vignesh C M
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)
37 views

Unit III Shell Scripting

Uploaded by

Vignesh C M
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/ 10

Unit III Shell Scripting: Types of shell, Basic shell configuration for bourne and bash shell:

/etc/profile, /etc/bashrc, ~/.bash_profile, ~/.bash_login, ~/.profile, ~/.bashrc, ~/.bash_logout,


~/.bash_history. Bourne shell scripts, script execution, variables and parameters, Control
structures - Shell if then else, Shell if then elif, Shell for loop, Shell while loop, Shell until
loop , Shell case, Shell function.
UMASK
UMASK in Linux systems is known as User Mask or it is also called as User file creation
Mask. This is a base permission or default permission when a new file or folder is created in
the Linux machine. Umask is a system variable .The umask command is used to set this
mask, or to show you its current value. To view your system's current umask value, enter the
command:
Umask
which will return your system's umask as a four-digit octal number,
for example: 0002 First 0 represents it is an octal number
SHELL PROGRAMMING
Shell
Shell is an interface between user and the kernel . Simply the shell is a program that takes
your commands from the keyboard and gives them to the operating system to perform .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.

Types of Shell in linux

. Shell is a user program or it's environment provided for user interaction. Shell is an command
language interpreter that executes commands read from the standard input device (keyboard)
or from a file.
sh
The Bourne shell, called "sh," is one of the original shells, developed for Unix computers by
Stephen Bourne at AT&T's Bell Labs in 1977. Its long history of use , many software
developers are familiar with it. It offers features such as input and output redirection, shell
scripting with string and integer variables, and condition testing and looping.
1. Bash(bourne-Again shell)
Bash (Bourne-Again SHell): Bash is the most common and widely used shell in
Linux. It is the default shell for most Linux distributions and is compatible with the Bourne
shell (sh) and its derivatives.
2. Bourne Shell
The Bourne shell (sh) is one of the original Unix shells and is the ancestor of many of
the shells used in Linux today. It was written by Stephen Bourne at Bell Labs in the
early 1970s and was the default shell in Unix for many years.
The Bourne shell is a command-line interpreter that provides basic functionality for
running commands, executing scripts, and managing files and directories. It supports
variables, loops, conditional statements, and other programming constructs that allow
users to create simple scripts and automate tasks.Although the Bourne shell is no
longer the default shell in most Linux distributions,
3. csh
Developers have written large parts of the Linux operating system in the C and C++
languages. Using C syntax as a model, Bill Joy at Berkeley University developed the "C-
shell," csh, in 1978. It has two advantages over bash shell.It allows aliasing of commands.
Another benefit is C shell has command history features.
ksh
David Korn developed the Korn shell, or ksh, about the time tcsh was introduced. Ksh
improves the functionality by adding floating-point arithmetic, job control, command
aliasing and command completion. AT&T held proprietary rights to ksh until 2000, when it
became open source.
Basic Shell configuration files
, ~/.profile, ~/.bashrc, ~/.bash_logout, ~/.bash_history
/etc/profile
It contains Linux system wide environment and startup programs. It is used by all users
with bash, ksh, sh shell. Usually used to set PATH variable, user limits, and other settings for
user. It only runs for login shell.

/etc/bashrc

On systems offering multiple types of shells, it might be better to put Bash-specific


configurations in this file. This file is meant for setting command and functions used by
bash shell users.
Bash_profile
bash_profile is a configuration file for bash shell. bash_profile is executed to configure your
shell before the initial command prompt.
bash-login
In Linux, the bash-login configuration file is a script that is executed by the Bash shell when
a user logs in to the system. This file is used to set up the environment for the user and can
contain various settings and configurations.
The bash-login configuration file is located in the user's home directory and is named
".bash_profile". If this file does not exist, the shell will look for a file named ".bash_login",
and if that does not exist, it will look for a file named ".profile".
Some common settings that can be configured in the bash-login configuration file include
setting environment variables, setting the system path, defining aliases, and running scripts or
programs at login.
SHELL SCRIPTING
A shell script have syntax just like any other programming language.
shell script comprises following elements –
 Shell Keywords .
 Shell Variables
 Shell commands
 Functions
 Control flow
Shell Variables(Variable handling in shell)
Shell variables are an integral part of shell programming. They provide the ability to store and
manipulate information with in the shell program.. You can create or destroy any number of
variables as needed to solve the problem at hand. All variables are considered as string type
The rules for building shell variables are as follow:

 variable name is any combination of alphabets digits and an underscore (‘_’).


 No commas or blanks are allowed within a variable name.
 The first character of a variable name must either be an alphabet or an underscore.
 Variables name should be of any reasonable length.
Variable name are case sensitive. That is, name, NAME, Name, Name are all different
variables
Shell keywords
Keywords are the word whose meaning has already been explained to the shell. The
keyword cannot be used as a variable name because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the shell. The keywords are also
called ‘Reserved words’.Shell keywords

echo if until trap


read else case wait
set fi esac eval
unset while break exec
readonly do continue unlimit
shift done exit unmask
export for return

Assigning Values to Variables


We can assign values to shell variables using simple assignment operator. For example,
name=John
age=20
Note that while assigning values to variables using the assignment operator ‘=’, there should
be no space on either side of =. If you leave a space the shell will try to interpret the value being
assigned as a command to be executed.
(a) Unix-defined variables or System variables:
These are standard variables which are always accessible. The shell provides the values for
these variables. These variables are usually used by the system itself and govern the
environment we work under. If we so desire we can change the values of these variables as per
our preferences and customize the system environment.
The $ prompt that we see in the default value of the Unix-defined variable PS1 standing for
system prompt.
Variable Meaning
PS2 The system prompt 2, default value is ”>”

PATH Defines the path which the shell must search in


order to execute any command or file

Defines the internet Field separator, which is


IFS space, a tab or a newline.

(b) User-defined variables:


These are defined and used most extensively in shell programming
The variable length can be of any reasonable length and may constitute alphabets, digts and
underscores. However the first character must be an alphabet or an underscore.
$a=20
This statement has defined a variable a and has assigned a value ‘20’ to it. The shell may be
made to display the value of the variable using echo.
$ echo $a
20
The $ as mentioned earlier causes the value of a to get displayed. Omitting the $ would simply
treat a as a character to be echoed.
$ echo a
a

Unchanging Variables

In some applications a need may arise for variables to have a constant or fixed value. For
instance, if we want that a’s value should always remain 20 and not changed, we can achieve
this by saying,

$ a=20
$ readonly a
When the variables are made readonly, the shell does not allow as to change their values. All
such variables can be listed by entering readonly at the $ prompt.

Positional Parameters

On many occasions we need to convey information to a program. For this the shell uses
something called ‘positional parameters’. These can be thought of as variables defined by the
shell. They are nine in number, named $1 though $9.

Passing Command Line Arguments/Positional parameters


Command-line arguments are parameters that are passed to a script while executing them
in the 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 help make shell scripts interactive for the users. command-line
arguments are an essential part of any practical shell scripting uses.

The bash shell has special variables reserved to point to the arguments which we pass through
a shell script. Bash saves these variables numerically ($1, $2, $3, … $n)

Here, the first command-line argument in our shell script is $1, the second $2 and the third is
$3. This goes on till the 9th argument. The variable $0 stores the name of the script or the
command itself.

Conditional Statements
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
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 (case…..esac)


The basic syntax of the case...esac statement is to give an expression to evaluate and to execute
several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If
nothing matches, a default condition will be used.
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac

Here the string word is compared against every pattern until a match is found. The statement(s)
following the matching pattern executes. If no matches are found, the case statement exits
without performing any action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump
to the end of the entire case statement. This is similar to break in the C programming language.
*) represent the default case
[])represent the range of values
? represents any character
Examples
[0-9] represent the range of digits 0 to 9
[aeiou]*)represent the word starts with aeiou
*[0-9])represents the word ends with a digit
???) represent the word is three lettered
Looping statements in shell
Types of loops
1. Until loop
2. While loop
3. For loop
Until loop
The until loop is useful when you need to execute a set of commands until a condition is true.
Syntax
until [ condition ]
do
statement 1
statement 2
done

While Loop
The while loop enables you to execute set of commands repeatedly until some condition
occurs.it usually used when you need to manipulate the value of a variable repeatedly.

Syntax

while [ condition ]
do
statement 1
statement 2
done

For loop

for [ variable_name ] in ...


do
statement 1
statement 2
statement n
done

Example

for no in {1..10}
do
echo $no
done

Test command
The test command evaluates the Expression parameter, and if the expression value is True,
returns a zero (True) exit value. Otherwise, the test command returns a nonzero (False) exit
value
There are three types of test command
1. Numerical tests
2. String test
3. File test
Numerical tests are used when comparisons between values of two numbers are to be done

Operator Meaning
-gt Greater than

-lt Less than

-ge Greater than

-le Less than or equal

-ne Not equal to

-eq Equal to

Example
If test $a –eq 0
File test
The test command has several options for checking the status of a file
-s file True if the file exists and has a size greater
than 0
-f file True if the file exits and is not a directory
-d file True if the file exists and is a directory
-c file True if the file exists and is a character
special file
-r file True if the file exists and you have a read
permission to it
-w file True if the file exists and you have a write
permission to it
-x file True if the file exists and you have a execute
permission to it
-k file True if the file exists and its sticky bit is set

Example
If [ -w $filenme ]
String test
Condition Meaning
String1=string2 True if strings are same
String1!=string2 True if the strings are not equal
-z String True if the length of the string is zero
String True if the string is not a null string

Shell functions
Shell functions are similar to subroutines, procedures, and functions in other programming
languages. A function is a collection of statements that execute a specified task. Using
functions to perform repetitive tasks is an excellent way to create code reuse. Functions enable
you to break down the overall functionality of a script into smaller, logical subsections, which
can then be called upon to perform their individual tasks when needed.
Creating Functions
To declare a function, simply use the following syntax −
function_name () {
list of commands
}

Pass Parameters to a Function as command line arguments


You can define a function that will accept parameters while calling the function. These
parameters would be represented by $1, $2 and so on.
Invoking a function
You can invoke a function by using its name as command
Function return values
bash function can pass the values of a function's local variable to the main routine by using the
keyword return. the returned values are then stored to the default variable $?
Example
hello_world(){
echo "Hello World"
return
}
hello_world

You might also like