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

Control Structures

The document discusses various control structures in BASH shell scripting like loops and conditions. It describes different types of loops like while, for, and for-in loops. Conditions structures covered are if, else, elif, and case. Logical operators like &&, || and ! are also discussed. The document provides examples of using these control structures and conditions to write shell scripts.

Uploaded by

Sachin Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Control Structures

The document discusses various control structures in BASH shell scripting like loops and conditions. It describes different types of loops like while, for, and for-in loops. Conditions structures covered are if, else, elif, and case. Logical operators like &&, || and ! are also discussed. The document provides examples of using these control structures and conditions to write shell scripts.

Uploaded by

Sachin Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Ganesh Singh Engineering College Bikaner Page No.

1
Control Structures: Control structures allow to repeat commands and select some commands
over others. Control structure consist two things: a test and command. If test is successful, then
the commands are executed.
There are two different kinds of control structures: loops and conditions. A loop repeats
commands, whereas a condition executes a command when certain conditions are met. The
BASH shell has three loop control structures: while, for, and for-in. There are two condition
structures: if and case. The control structures have as their test the execution of a Linux
command. All Linux commands return an exit status after they have finished executing. If a
command is successful, its exit status will be 0. If the command fails for any reason, its exit
status will be a positive value referencing the type of failure that occurred. The control structures
check to see if the exit status of a Linux command is 0 or some other value. In the case of the if
and while structures, if the exit status is a zero value, then the command was successful and the
structure continues.

Test Operations: With the test command, you can compare integers, compare strings, and even
perform logical operations. The command consists of the keyword test followed by the values
being compared, separated by an option that specifies what kind of comparison is taking place.
The option can be thought of as the operator, but it is written, like other
options, with a minus sign and letter codes.
$test arg1 -option arg2 : To tests the numeric operation
$test string1 = string1 : To tests both strings are identical or not
Bash Shell Test operators for integer comparisons
Operator Function
-gt Greater Than
-lt Less Than
-ge Greater Than Equal To
-le Less Than Equal To
-eq Equal To
-ne Not Equal To
String Comparisons
-z Tests for empty string
= Equal Strings
!= Not Equal Strings
Logical Operators
-a Logical AND
-o Logical OR
! Logical NOT
Ganesh Singh Engineering College Bikaner Page No. 2
File Tests
-f Returns True if file exists and file is a regular file
-s Returns true if file is not empty
-r Returns true if file is readable
-w Returns true if file can be written to, modified
-x Returns true if file is executable
-d Returns true if filename is a directory name

e.g.
$ n=5
$ test $n eq 10
1
$ test $n eq 5
0
$ [ $word = hello ]

ote: The brackets themselves must be surrounded by white space: a space, TAB, or ETER.
Without the spaces, it would be invalid.

BASH Shell Control Structures
========================
Condition Control Structures: if, else, elif, case
Function
if command then
command if executes an action if its test command is true.
fi
if command then
command if-else executes an action if the exit status of its test
else
command command is true; if false, then the else action is executed.
fi
if command then
command elif allows you to nest if structures, enabling selection
elif command then among several alternatives; at the first true if structure, its
command commands are executed and control leaves the entire elif
else structure.
command
fi

case string in case matches the string value to any of several patterns; if a
pattern) pattern is matched, its associated commands are executed.
command;;
esac

Ganesh Singh Engineering College Bikaner Page No. 3
command && command The logical AND condition returns a true 0 value if both
commands return a true 0 value; if one returns a non-zero
value, then the AND condition is false and also returns a
non-zero value.

command || command The logical OR condition returns a true 0 value if one or the
other command returns a true 0 value; if both commands
return a non-zero value, then the OR condition is false and
also returns a non-zero value.

! command The logical NOT condition inverts the return value of the
command.

Loop Control Structures: while, until, for, for-in, select
while command
do
command while executes an action as long as its test command is true.
Done

until command
do
command until executes an action as long as its test command is false.
Done

for variable in list-values
do for-in is designed for use with lists of values; the variable
command operand is consecutively assigned the values in the list.
done

BASH Shell Control Structures (Condition Control Structures: if, else, elif, case)

for variable
do for is designed for reference script arguments; the variable
command operand is consecutively assigned each argument value.
done

select string in item-list
do select creates a menu based on the items in the item-list; then
command it executes the command; the command is usually a case.
done

Example:
$vim listfilesize.sh
echo Enter s to list file sizes
echo otherwise all file information is listed.
echo -n "Please enter option: "
Ganesh Singh Engineering College Bikaner Page No. 4
read choice
if [ "$choice" = s ]
then
ls -s
else
ls -l
fi
echo Good-bye

To execute the program
$sh listfilesize.sh

Enter s to list file sizes
otherwise all file information is listed.
Please enter option: s



Example: vim forloop.sh
For NAME in ganesh rishiraj vinod rajkumar
do
[email protected]
MESSAGE=Today is the last date of project submission!!
Echo $MESSAGE | mail s Remainder $ADDRESS
done

ote: The value list can be specified separated by a space-delimited or we can also specify a file
name. e.g.

for USER in $(grep bash /etc/passwd)
or
for FILE in *.c

To perform a loop for a specific number of times or loop through a sequence of numbers. The
sequence notation is specified by {1..100} which is equivalent to numbers from 1 to 100. We can
Ganesh Singh Engineering College Bikaner Page No. 5
also use bashs built-in sequence notation or the seq command. e.g. seq 1 10 or seq 0 10 100
would count by tens from 0 to 100.

Example
#!/bin/bash
#alive.sh
#Check hosts from 192.168.0.1-192.168.0.30 are alive or not
for n in {1..30};
do
host=192.168.0.$n
ping c2 $host &> /dev/null
if [ $? = 0 ]; then
echo $host Machine is alive
else
echo $host Machine is down
fi
done


Here Document: It is a special-purpose code block. It uses a form of I/O redirection to feed a
command list to an interactive program or a command, such as ftp, cat, or the ex text editor.

COMMAND <<InputComesFromHERE
...

InputComesFromHERE

A limit string delineates (frames) the command list. The special symbol << designates the limit
string. This has the effect of redirecting the output of a file into the stdin of the program or
command. It is similar to interactiveprogram < command-file, where command-file contains.

Sends broadcast message to everyone logged in

#!/bin/bash
wall <<ENDOFMESSAGE
Today at 2PM File Server is down for maintenance work
# ------------------------------------------------------------------
# ------------------------------------------------------------------
ENDOFMESSAGE

The - option to mark a here document limit string (<<-LimitString) suppresses leading tabs (but
not spaces) in the output. This may be useful in making a script more readable.
cat <<-ENDOFMESSAGE
This is line 1 of the message.
This is line 2 of the message.
This is the last line of the message.
ENDOFMESSAGE
Ganesh Singh Engineering College Bikaner Page No. 6
A here document supports parameter and command substitution. It is therefore possible to pass
different parameters to the body of the here document, changing its output accordingly.

CMDLINEPARAM=1
if [ $# -ge $CMDLINEPARAM ]
then
NAME=$1

else
NAME="Ganesh Singh"
Fion

RESPONDENT="the author of this fine script"
cat <<ENDOFMESSAGE
Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.
ENDOFMESSAGE

A here document script to upload files onto server

#!/bin/bash
# upload.sh
# Upload file pair (backup.zip, backup.tar.gz)
E_ARGERROR=85
if [ -z "$1" ]
then
echo "Usage: `basename $0` Filename-to-upload"
exit $E_ARGERROR
fi
Filename=`basename $1` # Strips pathname out of file name.
Server="ecb.ac.in"
Directory="/home/public"
Password="here your password"
ftp -n $Server <<End-Of-Session # -n option disables auto-logon
user anonymous "$Password" # If this doesn't work, then try with your username
binary
bell # Ring 'bell' after each file transfer.
cd $Directory
put "$backup.zip"
put "$backup.tar.gz"
bye
End-Of-Session
exit 0
-----------------------------------------------------------------------------------------------------------


Ganesh Singh Engineering College Bikaner Page No. 7
A script that generates another script
#!/bin/bash
# generate-script.sh
OUTFILE=generated.sh # Name of the file to generate.
# 'Here document containing the body of the generated script.
(
cat <<'EOF'
#!/bin/bash
echo "This is a generated shell script."
# Note that since we are inside a subshell,
# we can't access variables in the "outside" script.
echo "Generated file will be named: $OUTFILE"
a=7
b=3
let "c = $a * $b"
echo "c = $c"
exit 0
EOF
) > $OUTFILE
# -----------------------------------------------------------
if [ -f "$OUTFILE" ]
then
chmod 755 $OUTFILE # Make the generated file executable.
else
echo "Problem in creating file: \"$OUTFILE\""
fi
# This method can also be used for generate C programs, Perl, Python programs, Makefiles,
exit 0
------------------------------------------------------------------------------------------------------------------

It is possible to set a variable from the output of a here document. This is actually a
devious form of command substitution

variable=$(cat <<SETVAR
This variable
runs over multiple lines.
SETVAR)
echo "$variable"
-------------------------------------------------------------------------------------------------------------------------------
Here document can be used to supply input to a function in the same script.

#!/bin/bash
# function.sh
GetData ()
{
read firstname
read lastname
read address
read city
Ganesh Singh Engineering College Bikaner Page No. 8
read state
read zipcode
}
GetData <<RECORD1
Ganesh
Singh
159, UIT Qtrs
Bikaner
Rajasthan
334004
RECORD1
echo
echo "$firstname $lastname"
echo "$address"
echo "$city, $state $zipcode"
exit 0
-----------------------------------------------------------------------------------------------------------------------------
It is possible to use : as a dummy command accepting output from a here document.
This, in effect, creates an "anonymous" here document.

#!/bin/bash
: <<TESTVAR
${HOSTNAME?}${USER?}${MAIL?} # Print error message if any variables not set.
TESTVAR
exit $?
----------------------------------------------------------------------------------------------------------------
: <<DEBUG
for file in *
do
cat "$file"
done
DEBUG
---------------------------------------------------------------------------------------------------------------
Creates a 2-line dummy file

#!/bin/bash
# Non-interactive use of 'vi' to edit a file.
# Emulates 'sed'.
E_BADARGS=65
if [ -z "$1" ]
then
echo "Usage: `basename $0` filename"
exit $E_BADARGS
fi
TARGETFILE=$1
# Insert 2 lines in file, then save.

vi $TARGETFILE <<LimitString
i
Ganesh Singh Engineering College Bikaner Page No. 9
This is line 1 of the example file.
This is line 2 of the example file.
^[
ZZ
LimitString
exit 0
-------------------------------------------------------------------------------------------------------
The above script could just as effectively have been implemented with ex, rather than vi. Here
documents containing a list of ex commands are common enough to form their own category,
known as ex scripts.

#!/bin/bash
ORIGINAL=Ganesh
REPLACEMENT=Ajay
for word in $(fgrep -l $ORIGINAL *.txt)
do
ex $word <<EOF
:%s/$ORIGINAL/$REPLACEMENT/g
:wq
EOF
# :%s is the "ex" substitution command.
# :wq is write-and-quit.
done
-----------------------------------------------------------------------------------------------------------------

You might also like