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

124-Linux Shell Scripting

This document provides an overview of shell scripting, focusing on structured commands like 'while', 'break', and 'continue', as well as handling user input through command line parameters and the 'read' command. It includes examples and exercises to illustrate concepts such as looping, reading parameters, and processing options. Additionally, it covers standard Linux command line options and techniques for reading user input, including silent reading for sensitive data.

Uploaded by

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

124-Linux Shell Scripting

This document provides an overview of shell scripting, focusing on structured commands like 'while', 'break', and 'continue', as well as handling user input through command line parameters and the 'read' command. It includes examples and exercises to illustrate concepts such as looping, reading parameters, and processing options. Additionally, it covers standard Linux command line options and techniques for reading user input, including silent reading for sensitive data.

Uploaded by

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

Shell Scripting

Session 04

Vahab Shalchian (ITIL v3 , LPIC-1 , LPIC-2 , LPIC-3)


Structured
Commands (while)
The while Command
The while command allows you to define a command to test, then
loop through a set of commands for as long as the defined test
command returns a zero exit status. It tests the test command at the
start of each iteration. When the test command returns a non-zero
exit status, the while command stops executing the set of
commands.

The format of the while command is:


while test command
do
other commands
done
Structured
Commands (while)
Example:

var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
Structured
Commands (while)
Exercise : Write a script that asks a yes/no question from user and
does not continue until yes or no is entered.

answer=""
while [ "$answer" != "yes" ] && [ "$answer" != "no" ]
do
echo "Do you want to exit ? "
read answer
done
Controlling the
Loop
The break command
The break command is a simple way to escape out of a loop in
progress. You can use the break command to exit out of any type of
loop, including for and while.

for var1 in {1..10}


do
if [ $var1 -eq 5 ]
then
break
fi
echo $var1
done
Controlling the
Loop
There may be times when you’re in an inner loop but need to stop
the outer loop. The break command includes a single command line
parameter value:
break n
where n indicates the level of the loop to break out of. By default, n
is one, indicating to break out of the current loop. If you set n to a
value of two, the break command will stop the next level of the
outer loop:
Controlling the
Loop
The continue command
The continue command is a way to prematurely stop processing
commands inside of a loop but not terminate the loop completely.
This allows you to set conditions within a loop where the
shell won’t execute commands.

for var1 in {1..10}


do
if [ $var1 -gt 3 ] && [ $var1 -lt 7 ]
then
continue
fi
echo $var1
done
Handling User
Input
Command Line Parameters

The most basic method of passing data to your shell script is by


using command line parameters. Command line parameters allow
you to add data values to the command line when you execute the
script:
$ ./add 10 30
Handling User
Input
Reading parameters
The bash shell assigns special variables, called positional parameters, to all
of the parameters entered in a command line. This even includes the name
of the program the shell executes. The positional parameter variables are
standard numbers, with $0 being the name of the program, $1 being the
first parameter, $2 being the second parameter, and so on, up to $9 for the
ninth parameter.

#!/bin/bash
echo "The first parameter is $1"

Remember, each of the parameters is separated by a space, so the shell


interpreted the space as just separating the two values. To include a space
as a parameter value, you must use quotation
marks (either single or double quotation marks)
Handling User
Input
Exercise : Write a script to calculate the factorial of a number given
as parameter

#!/bin/bash
fact=1
i=1
while [ $i -le $1 ]
do
fact=$[ $fact * $i ]
i=$[ $i + 1 ]
done
echo "The factorial is $fact"

$ ./factorial.sh 5
Handling User
Input
Testing parameters
You need to be careful when using command line parameters in your
shell scripts. If the script runs without the parameters, bad things
can happen.
-n is a string operator that checks if a string is not null.
-z is a string operator that check if a string is null.
#!/bin/bash
if [ -n "$1" ]
then
echo "The first parameter is $1"
else
echo "First parameter is not entered, exiting …"
exit 1
fi
Handling User
Input
Special Parameter Variables

Counting parameters
The special $# variable contains the number of command line
parameters included when the script was run. You can use this
special variable anywhere in the script, just as a normal variable:

#!/bin/bash
echo There were $# parameters supplied.
Handling User
Input
So you have the ability to test the number of parameters present
before trying to use them:

#!/bin/bash
if [ $# -ne 2 ]
then
echo Usage: script_name a b
else
…….
fi
Handling User
Input
Grabbing all the data
There are situations where you’ll want to just grab all of the
parameters provided on the command line and iterate through all of
them.

Both of $* and $@ variables include all of the command line


parameters within a single variable.
The $* variable takes all of the parameters supplied on the
command line as a single word.
The $@ variable on the other hand, takes all of the parameters
supplied on the command line as separate words in the same string.
It allows you to iterate through the value, separating out each
parameter supplied. This is most often accomplished using the for
command.
Handling User
Input
In the following example the result would be the same.

#!/bin/bash
echo "Input parameters using method 1 : $*"
echo "Input parameters using method 2: $@"
Handling User
Input
#!/bin/bash
count=1
for param in "$*"
do
echo "\$* Parameter #$count = $param"
count=$[ $count + 1 ]
done
echo "##########"
count=1
for param in "$@"
do
echo "\$@ Parameter #$count = $param"
count=$[ $count + 1 ]
done
Handling User
Input
Shifting Parameters

The shift command shifts the command line parameters in their


relative positions.
When you use the shift command, it "downgrades" each parameter
variable one position by default. Thus, the value for variable $3 is
moved to $2, the value for variable $2 is moved to $1, and the value
for variable $1 is discarded (note that the value for variable $0, the
program name, remains unchanged).
Handling User
Input
#!/bin/bash
# demonstrating the shift command
count=1
while [ -n "$1" ]
do
echo "Parameter #$count = $1"
count=$[ $count + 1 ]
shift
done

You can perform a multiple location shift by providing a parameter


to the shift command. Just provide the number of places you want
to shift:
shift 2
Handling User
Input
Processing simple options

#!/bin/bash
# extracting command line options as parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option";;
esac
shift
done
Handling User
Input
Processing options with values - Using the getopts command

It processes the parameters it detects in the command line one at a


time each time it’s called.
When it runs out of parameters, it exits with an exit status greater
than zero. This makes it great for using in loops to parse all of the
parameters on the command line.
The format of the getopts command is:
getopts optstring variable

The optstring defines the valid option letters used in the command
line. It also defines which option letters require a parameter value.
Handling User
Input
The OPTARG environment variable contains the value to be used if
an option requires a parameter value.

while getopts :ab:c opt


do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";;
c) echo "Found the -c option" ;;
*) echo "Unknown option: $opt";;
esac
done
Handling User
Input
Standardizing Options

When you create your shell script, obviously you’re in control of


what happens. It’s completely up to you as to which letter options
you select to use, and how you select to use them.
However, there are a few letter options that have achieved
somewhat of a standard meaning in the Linux world. If you leverage
these options in your shell script, it’ll make your scripts more
user-friendly.
Handling User
Input
Common Linux Command Line Options

Option Description
-a Show all objects
-f Specify a file to read data from
-h Display a help message for the command
-n Do nothing, just display what will happen
-o Specify an output file to redirect all output to
-q Run in quiet mode
-r Process directories and files recursively
-s Run in silent mode
-v Produce verbose output
-y Answer yes to all questions
Handling User
Input
Getting User Input - Basic reading
The read command accepts input from the standard input (the
keyboard) and places the data into a standard variable

#!/bin/bash
echo -n "Enter your name: "
read name
echo "Hello $name"

Tip: If you need to use another value after variable without space
you need to use braces around variable name :
item=A
echo "This is ${item}1"
Handling User
Input
The read command includes the -p option, which allows you to
specify a prompt directly in the read command line:

$ read -p "Please enter your name : " name

You can use the -t option specify a timer. The -t option specifies the
number of seconds for the read command to wait for input. When
the timer expires, the read command returns a non-zero exit status:
if read -t 5 -p "Please enter your name: " name ; then
echo "Hello $name, welcome to my script"
else
echo
echo "Sorry, too slow!"
fi
Handling User
Input
Silent reading
There are times when you need input from the script user, but you
don’t want that input to display on the monitor. One example could
be when entering passwords.

The -s option prevents the data entered in the read command from
being displayed on the monitor (actually, the data is displayed, but
the read command sets the text color to the same as the
background color).

read -s -p "Enter your password: " pass


echo
echo "You entered : $pass"
Handling User
Input
Reading from a file

Example:

#!/bin/bash

count=1
cat /etc/passwd | while read line
do
echo "Line $count: $line"
count=$[ $count + 1]
done
Handling User
Input
Example 2:

#!/bin/bash

count=1
while read line
do
echo "Line $count: $line"
count=$[ $count + 1]
done < /etc/passwd

You might also like