0% found this document useful (0 votes)
31 views15 pages

3CS LSP Unit 4

Uploaded by

marveledit145
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)
31 views15 pages

3CS LSP Unit 4

Uploaded by

marveledit145
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/ 15

UNIT – 4: SHELL PROGRAMMING

SHELL SCRIPT-WRITING AND EXECUTING


Shell Scripting: Shell Scripting is an open-source computer program designed to be run by the
Unix/Linux shell. Shell Scripting is a program to write a series of commands for the shell to
execute. It can combine lengthy and repetitive sequences of commands into a single and simple
script that can be stored and executed anytime which, reduces programming efforts.

What is Shell?: Shell is a UNIX term for an interface between a user and an operating system
service. Shell provides users with an interface and accepts human-readable commands into the
system and executes those commands which can run automatically and give the program’s
output in a shell script. An Operating is made of many components, but its two prime
components are –
 Kernel
 Shell

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.

How to Write Shell Script in Linux/Unix: Shell Scripts are written using text editors. On your
Linux system, open a text editor program, open a new file to begin typing a shell script or shell
programming, then give the shell permission to execute your shell script and put your script at
the location from where the shell can find it. Let us understand the steps in creating a Shell
Script:
1. Create a file using a vi editor (or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
“#!” is an operator called shebang which directs the script to the interpreter location. So, if we
use”#! /bin/sh” the script gets directed to the bourne-shell.

PARAMETERS & VARIABLES


Parameters: Shell script parameters are the entities that are used to store variables in Shell.
Among these parameters, the named spaces are there in the memory and they permit us to access
these stored variables
Why do we need Shell Script Parameters?: To add additional features to the command while
working with shell script can be achieved by using parameters i.e. by the help of command-line
options along with the arguments. Parameters are used to help in choosing options from the
command line

Types of Parameters
 Variables: The variables which are a type of parameter are generally managed by the
users or the system. We can take an example of $var which is a variable parameter. The
system sets $var, but this variable parameter can be written by the user. So it’s not read-
only, like the special parameters.
 Special Parameters: The special parameters are read-only which are maintained by the
shell. The special parameters are with a predefined meaning. Below are the various
special parameters:
Parameters Description
$# This parameter represents the total no of arguments passed to the script
$0 This parameter represents the script name
$n This parameter represents the arguments corresponding to a script when a
script is invoked.
$* This parameter describes the positional parameters to be distinct by space
$$ This parameter represents the process ID of a shell in which the execution is
taking place
$! This parameter represents the process number of the background that was
executed last
$@ This parameter is similar to the parameter $*
$? This parameter represents exit status of the last command that was executed.
Here 0 represents success and 1 represents failure
$_ This parameter represents the command which is being executed previously
$- This parameter will print the current options flags where the set command can
be used to modify the options flags.

Advantage of Shell Script Parameters: One of the main advantages of using the parameters is
that while passing the arguments to the function or a script, the code can be reused again and
again

Rules and Regulation for Shell Script Parameters


 Special parameters are used to deliver information to programs by specifying the
arguments in the command line. $n can be described by one or more digits, such as $1,
$2, $3…., where $1, $2, $3 etc are the arguments to the command. The positional
parameters are generally passed along with the command when it is invoked. But the
parameter must be enclosed within {} where the parameter consists of more than 1 digit.
 The reading of a variable is called parameter expansion. It can be described as below:
$var=apple
$ echo “The variable is $var”
 The default values can be provided for variables by using brackets or test commands. If a
parameter which is not declared having a null value, then we need to use the default
value. Also, parameters are checked to see if they represent specific words or directories
or file names etc.
 The double quotes are used to treat most of the special characters as letters.
$var=apple
$echo“var$var”
$ echo $var“abcd”
 The above command will show the below result
$varapple
$ appleabcd
 To read $ as a normal character, we need to use a single quote as below.
$echo‘var$var’
$ var$var
 In order to perform arithmetic operations, we need to use $(( )) as below.
$a=5
$echo5+9$a+9
$echo$((5+9))
$echo $(($a+9))
 The result of $echo 5+9 $a+9 is 5+9 5+9. But the result of $echo $((5+9)) and $echo
$(($a+9)) is 14.

Variables:
A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data.

A variable is nothing more than a pointer to the actual data. The shell enables you to create,
assign, and delete variables.

Variable Names: The name of a variable can contain only letters (a to z or A to Z), numbers
(0 to 9) or the underscore character (_). By convention, Unix shell variables will have their
names in UPPERCASE. The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!

Defining Variables: Variables are defined as follows −


variable_name=variable_value
For example −
NAME="Zara Ali"
The above example defines the variable NAME and assigns the value "Zara Ali" to it.
Variables of this type are called scalar variables. A scalar variable can hold only one value at
a time.

Accessing Values: To access the value stored in a variable, prefix its name with the dollar
sign ($). For example, the following script will access the value of defined variable NAME
and print it on STDOUT −
#!/bin/sh
NAME="Zara Ali"
echo $NAME
The above script will produce the following value −
Zara Ali

Read-only Variables: Shell provides a way to mark variables as read-only by using the read-
only command. After a variable is marked read-only, its value cannot be changed. For
example, the following script generates an error while trying to change the value of NAME −
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
The above script will generate the following result −
/bin/sh: NAME: This variable is read only.

Unsetting Variables: Unsetting or deleting a variable directs the shell to remove the variable
from the list of variables that it tracks. Once you unset a variable, you cannot access the
stored value in the variable. Following is the syntax to unset a defined variable using the unset
command −
unset variable_name
The above command unsets the value of a defined variable. Here is a simple example that
demonstrates how the command works −
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME

Types of variable: The shell is a command-line interpreter for Linux and Unix systems. It
provides an interface between the user and the kernel and executes commands. A sequence of
commands can be written in a file for execution in the shell. It is called shell scripting. It
helps to automate tasks in Linux. In shell scripting there are three main types of variables are
present. They are –
1. Local Variables
2. Global Variables or Environment Variables
3. Shell Variables or System Variables
1. Local Variable: A local variable is a special type of variable which has its scope only
within a specific function or block of code. Local variables can override the same variable
name in the larger scope. Let’s understand this concept using an example –
Shell script:
#!/bin/sh
getName(){
NAME=SATYAJIT #local variable
echo "$NAME (from function)" #valid if called using function
}
echo "$NAME - (outside function)" #invalid here
getName

2. Global Variables: A global variable is a variable with global scope. It is accessible


throughout the program. Global variables are declared outside any block of code or function.
Let’s understand this concept using an example –
Shell script:
#!/bin/sh
NAME=SATYAJIT #global variable
getName(){
echo "$NAME (from function)"
}
echo "$NAME - (outside function)"
getName

3. Shell Variables: These are special types of variables. They are created and maintained by
Linux Shell itself. These variables are required by the shell to function properly. They are
defined in Capital letters and to see all of them, we can use set / env / printenv command
Variable Name Description Usage
Holds the version of this
BASH_VERSION instance of bash. echo $BASH_VERSION
Provides a home directory of
HOME the current user. echo $HOME
HOSTNAME Provides computer name echo $HOSTNAME
USERNAME Provides username echo $USERNAME

COMMAND LINE ARGUMENTS


An argument, also called command line argument, can be defined as input given to a command
line to process that input with the help of given command. Argument can be in the form of a file
or directory. Arguments are entered in the terminal or console after entering command. They can
be set as a path. We can also write more than one argument together, they will be processed in
the order they are written.
Syntax:
<command> <argument>
<command> <argument> <argument>
Exapmle:
cd Downloads
ls sample
cd /home/sssit/Desktop
file javatpoint jtp.txt (With two arguments)

White space removal: White spaces are invisible but take up the spaces. While executing the
command these white spaces are automatically removed from the output. Here, we'll
use echo command which is used to print the output that it receives from the shell.
Syntax:
echo <typedTtext>

Single and double quotes: If you want white spaces to be displayed then use them within the
quotes. You can use single as well as double quotes. Write argument within the quotes and print
it with 'echo' command. Linux 'echo' command will consider the whole data as a single argument
within the quotes.
Syntax:
echo < 'typedTtext' >
echo < "typedTtext" >

echo –e: Linux 'echo -e' command is used with '\n' and '\t' to start a new line and add a tab space
respectively. It works within single as well as double quotes.
Syntax
echo -e < 'typedTtext' >
echo -e < 'typedTtext" >

EXIT AND EXIT STATUS OF A COMMAND


Every Linux or Unix command executed by the shell script or user has an exit status. Exit status
is an integer number. 0 exit status means the command was successful without any errors. A non-
zero (1-255 values) exit status means command was a failure.

How to find out the exit code of a command: You need to use a particular shell variable called
$? to get the exit status of the previously executed command. To print $? variable use the echo
command or printf command:
date
echo $?
date-foo-bar
printf '%d\n' $?

How to use exit codes in shell script


command
status=$?
## 1. Run the date command ##
cmd="date"
$cmd
## 2. Get exist status and store into '$status' var ##
status=$?
## 3. Now take some decision based upon '$status' ##
[ $status -eq 0 ] && echo "$cmd command was successful" || echo "$cmd failed"

A sample shell script to get the exit code of a command


#!/bin/bash
#
# Sample shell script to demo exit code usage #
#
## find ip in the file ##
grep -q 192.168.2.254 /etc/resolv.conf

## Did we found IP address? Use exit status of the grep command ##


if [ $? -eq 0 ]
then
echo "Success: I found IP address in file."
exit 0
else
echo "Failure: I did not found IP address in file. Script failed" >&2
exit 1
fi

Recommend exit code for shell script


Exit status Description
1 Catchall for general errors

2 Misuse of shell built-ins (according to Bash documentation)

126 Command invoked cannot execute

127 Command not found

128 Invalid argument to exit command

128+n Fatal error signal “n”

130 Bash script terminated by Control-C

255* Exit status out of range

THE SET AND SHIFT COMMAND


Set Command: Linux set command is used to set and unset certain flags or settings within the
shell environment. These flags and settings determine the behavior of a defined script and help in
executing the tasks without facing any issue. The values of shell attributes and parameters can be
changed or displayed by using the set command.
Syntax:
set [options]

Turn debugging information on or off: The '-x' option is used with the set command to show
command and their arguments. It is useful for debugging the shell script.
To turn on the debugging information:
set -x
To turn off the debugging information:
set +x

Disable Bash's default behavior: To disable the default behavior of Bash, execute the
command as follows:
set -C

Stop a script immediately: To stop a script immediately, execute the following command:
set -e

Getting Help: If you get stuck during the use of the set command, you can access the help
documentation from your terminal. To access the help manual, execute the below command:
set --help

Shift Command: Shift is a built-in command in bash which after getting executed, shifts/move
the command line arguments to one position left. The first argument is lost after using shift
command. This command takes only one integer as an argument.
Syntax:
shift n
Here, n is the number of positions by which you want to shift command-line arguments to the
left if you do not specify, the default value of n is assumed to be 1 i.e shift works the same as
shift 1.

Example: Let’s create a shell script file named as sampleshift.sh as follows. The total number
of command-line arguments is represented by $#. Use the following command to create the
desired shell script file
vi sampleshift.sh
Now paste the following code:
#!/bin/bash
# total number of command-line arguments
echo "Total arguments passed are: $#"
# $* is used to show the command line arguments
echo "The arguments are: $*"
echo "The First Argument is: $1"
shift 2
echo "The First Argument After Shift 2 is: $1"
shift
echo "The First Argument After Shift is: $1"
LOGICAL OPERATORS
We use the logical operators to test more than one condition. Following are the logical operators
that we will be discussing.
Operator Description

-a Logical AND

-o Logical OR

1. Logical AND: The logical AND -a operator will give true if both the operands are true.
Otherwise, false. Truth table of logical AND operator.
A B A -a B

false false false

false true false

true false false

true true true


In the following example we will check if the number is even and greater than 10.
#!/bin/sh
echo "Enter a number: "
read a
if [ `expr $a % 2` == 0 -a $a -gt 10 ]
then
echo "$a is even and greater than 10."
else
echo "$a failed the test."
Fi

2. Logical OR: The logical OR -o operator will give true if any one of the operand is true. If
both operands are false then it will return false. Truth table of logical OR operator.
A B A -o B

false false false

false true true

true false true

true true true


In the following example we will check if entered number is either odd or less than 10.
#!/bin/sh
echo "Enter a number: "
read a
if [ `expr $a % 2` != 0 -o $a -lt 10 ]
then
echo "$a is either odd or less than 10."
else
echo "$a failed the test."
fi

IF, WHILE, FOR AND CASE CONTROL STATEMENTS


If Statement: The if statement is composed of the if keyword, the conditional phrase, and the
then keyword. The fi keyword is used at the end of the statement. The COMMANDS gets
executed if the CONDITION evaluates to True. Nothing happens if CONDITION returns
False; the COMMANDS are ignored. The basic syntax of an if statement is the following:
Syntax:
if CONDITION
then
COMMANDS
fi

Example: The following is an example script that will prompt you to input a number and then
it checks whether the given number is even.
echo -n "Enter Number: "
read x
if [ $((x%2)) == 0 ]; then
echo "Number is Even"
fi

While Loop: A while loop is a statement that iterates over a block of code till the condition
specified is evaluated to false. We can use this statement or loop in our program when do not
know how many times the condition is going to evaluate to true before evaluating to false.
Syntax:
while [ condition ];
do
# statements
# commands
done

If the condition is true then the commands inside the while block are executed and are iterated
again after checking the condition. Also if the condition is false the statements inside the
while block are skipped and the statements after the while block are executed.
Example
#!/usr/bin/bash
a=7
while [ $a -gt 4 ];
do
echo $a
((a--))
done
echo "Out of the loop"

For Loop: There are a couple of ways to use for loops depending on the use case and the
problem it is trying to automate.
 Simple For loop
 Range-based for loop
 Array iteration for loops
 C-Styled for loops
 Infinite for loop
1. Simple For loop: To execute a for loop we can write the following syntax:
Syntax:
#!/bin/usr/env bash
for n in a b c;
do
echo $n
done

2. Range-based for loop: We can use range-based for loops. In this type of loop, we can
specify the number to start, to stop, and to increment at every iteration (optional) in the
statement. There are two ways you can do this i.e. by mentioning the increment/decrementer
value and by incrementing by one by default.
Syntax:
#!/bin/usr/env bash
for n in {1..5};
do
echo $n
done

3. Array iteration for loops: We can iterate over arrays conveniently in bash using for loops
with a specific syntax. We can use the special variables in BASH i.e @ to access all the
elements in the array. Let’s look at the code:
Syntax:
#!/bin/usr/env bash
s=("football" "cricket" "hockey")
for n in ${s[@]};
do
echo $n
4. C-Styled for loops: As said earlier, we need to use the variables inside the for loops to
iterate over a range of elements. And thus, the C-styled for loops play a very important role.
Let’s see how we use them.
Syntax:
#!/bin/usr/env bash
n=7
for (( i=1 ; i<=$n ; i++ ));
do
echo $i
done

5. Infinite for loop: We don’t use this often but it is sometimes useful to get certain things
working. The syntax is quite easy and similar to the C-styled for loops.
Syntax:
#!/bin/usr/env bash
n=4
for (( ; ; ));
do
if [ $n -eq 9 ];then
break
fi
echo $n
((n=n+1))
done

Case Statement: Case statement in bash scripts is used when a decision has to be made
against multiple choices. In other words, it is useful when an expression has the possibility to
have multiple values. This methodology can be seen as a replacement for multiple if-
statements in a script.
Syntax:
case EXPRESSION in
Pattern_Case_1)
STATEMENTS
;;
Pattern_Case_1)
STATEMENTS
;;
Pattern_Case_N)
STATEMENTS
;;
*)
STATEMENTS
;;
Esac
Rules for case statement:
 A case statement begins with the case keyword which is followed by
an expression and the in the keyword.
 It ends with the esac keyword.
 Multiple pattern cases can be used separated by | operator.
 Closing parenthesis operator ‘)’ is used to end the pattern cases list.
 A pattern case can contain special characters.
 A pattern case and its body are termed as a clause.
 Pattern case body must be followed by ;;.
 In case an expression matches with two patterns cases then in such case the body
corresponding to the first matching pattern case that matches the expression is
executed.
 Like C provides default keyword for default statement, likewise in the Bash case
statement, we can use the wildcard asterisk symbol (*) and define a final pattern case
to define the default case.
 In case no pattern is matched, the return status is zero. Otherwise, the return status is
the exit status of the executed body of the matched pattern case.

FUNCTIONS
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. Using
functions to perform repetitive tasks is an excellent way to create code reuse. This is an
important part of modern object-oriented programming principles.

Creating Functions: To declare a function, simply use the following syntax −


function_name ()
{
list of commands
}

Example: Following example shows the use of function −


#!/bin/sh
# Define your function here
Hello ()
{
echo "Hello World"
}
# Invoke your function
Hello

Pass Parameters to a Function: You can define a function that will accept parameters while
calling the function. These parameters would be represented by $1, $2 and so on. Following is an
example where we pass two parameters Zara and Ali and then we capture and print these
parameters in the function.
#!/bin/sh
# Define your function here
Hello ()
{
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali

Returning Values from Functions: If you execute an exit command from inside a function, its
effect is not only to terminate execution of the function but also of the shell program that called
the function. Based on the situation you can return any value from your function using
the return command whose syntax is as follows −
Syntax:
return code

Example: Following function returns a value 10 −


#!/bin/sh
# Define your function here
Hello ()
{
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali

Nested Functions: One of the more interesting features of functions is that they can call
themselves and also other functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
#!/bin/sh
# Calling one function from another
number_one ()
{
echo "This is the first function speaking..."
number_two
}
number_two ()
{
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
LINUX ALIASES
Linux 'alias' command replaces one string from the shell with another string. It is a shell built-in
command. It converts a complicated command into a simpler command or in other words, it
creates a shortcut by replacing it with the simpler one.

Making 'alias' in command line creates a temporary 'alias'. Temporary aliases are only available
until you exit the shell. To make permanent 'alias' store it in bash startup files.

Note: There will be no space on either side of (=) sign while typing 'alias' command. Quotes are
necessary if there are more than one word in the string being aliased.

alias syntax:
alias <newName>=<command> (To create alias for commands)
alias <newName>=<'command arg1 arg2....'> (To create alias for more than one argument)
alias <newName>=<'/home/sssit/path/...'> (To create alias by a path)

Creating an alias: Here, we are going to use following options for creating an alias.
1. Creating alias for 'file' command as 'fi'
2. Creating alias for 'ls-l' command as 'll'
3. Creating alias with two arguments
4. Creating alias for a path

1. Creating alias for 'file' command as 'fi'


Syntax:
alias <newName>=<command>

2. Creating alias for 'ls-l' command as 'll'


Syntax:
alias <newName>=<'command'>

3. Creating alias with two arguments


Syntax:
alias <newName>=<'command arg1 arg2'>

4. Creating alias for a path


Syntax:
alias <newName>=<'/home/sssit/path/...'>

How to remove alias: With the help of 'unalias' command you can remove created alias.
Syntax:
unalias <createdAlias>

You might also like