Вы находитесь на странице: 1из 22

LINUX+ LAB SERIES (LX0-102)

Lab 11b: BASH Scripting


Document Version: 2015-04-30

This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where otherwise
noted, is licensed under the Creative Commons Attribution 3.0 Unported License.
Development was funded by the Department of Labor (DOL) Trade Adjustment Assistance Community College and Career Training
(TAACCCT) Grant No. TC-22525-11-60-A-48; The National Information Security, Geospatial Technologies Consortium (NISGTC) is an
entity of Collin College of Texas, Bellevue College of Washington, Bunker Hill Community College of Massachusetts, Del Mar College
of Texas, Moraine Valley Community College of Illinois, Rio Salado College of Arizona, and Salt Lake Community College of Utah.
This workforce solution was funded by a grant awarded by the U.S. Department of Labor's Employment and Training Administration.
The solution was created by the grantee and does not necessarily reflect the official position of the U.S. Department of Labor. The
Department of Labor makes no guarantees, warranties or assurances of any kind, express or implied, with respect to such
information, including any information on linked sites, and including, but not limited to accuracy of the information or its
completeness, timeliness, usefulness, adequacy, continued availability or ownership.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Contents
Introduction ........................................................................................................................ 2
Objective ............................................................................................................................. 2
Linux+ LX0-102 Exam Objectives ........................................................................................ 3
Lab Topology ....................................................................................................................... 4
Lab Settings ......................................................................................................................... 5
1 Shell Scripting Basics ................................................................................................... 6
2 Conditional Execution ............................................................................................... 13

1
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Introduction
This lab provides guidance on performing Lab 11b: BASH Scripting of the Linux+ LX0-102
course, using a NETLAB+ system. By performing this lab, students will learn how to work
with shell scripts.

Objective
The following tasks will be performed:
1. Create simple shell scripts.
2. Create shell scripts with conditional execution.

2
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Linux+ LX0-102 Exam Objectives


This lab will cover the topics for the following LX0-102 objectives:
105.2 Customize or write simple scripts
1. Use standard sh syntax (loops, tests).
2. Use command substitution.
3. Test return values for success or failure or other information provided by a
command.
4. Perform conditional mailing to the superuser.
5. Correctly select the script interpreter through the shebang(#!) line.
6. Manage the location, ownership, execution and suid-rights of scripts.
The following is a partial list of the used files, terms, and utilities:
a. for
b. while
c. test
d. if
e. read
f. seq

3
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Lab Topology

4
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Lab Settings
The information in the table below will be used to complete the lab. Additional details
will be provided within the task sections as required.
System

Username/Password

CentOS Server

sysadmin/netlab123

Ubuntu Server

sysadmin/netlab123

Fedora Workstation

sysadmin/netlab123

Ubuntu Workstation

sysadmin/netlab123

All Machines

root/netlab123

5
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Shell Scripting Basics

Shell scripting allows you to take a complex sequence of commands, place them into a
file and then run the file as a program. This saves you the time of having to type a long
sequence of commands that you routinely use.
This lab will focus on how to create simple shell scripts. For the purpose of this lab we
will assume that you know how to use an editor. Feel free to use the editor of your
choice: vi, nano, gedit or any other editor that you like.
1. Click on the Fedora Workstation icon in the pod topology to launch the virtual
machine.

2. The virtual machine will display a login screen. Make sure sysadmin is in the
user field. Enter the password netlab123 and press Enter.

6
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

3. Once you have logged in, a terminal window may appear. If it does not, click on
the Kickoff Application Launcher, the f, in the lower-left corner of the desktop.
In the search bar, type konsole and click on Konsole, which will launch a
terminal window:

7
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

4. To create a simple shell script, you just need to create a text file and add
commands. Create a file called sample.sh and add the following lines:
echo "Hello there!
cal

Here is the calendar for this month:"

Your output should be similar to the following:

5. To make it clear that this is a BASH shell script, we need to include a special line
at the top of the file called a "shbang" (or "shebang"). This line starts with #!
and then contains the path to the BASH shell executable. Add the following line
at the top of the sample.sh file:
#!/bin/bash

8
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

6. One way that we can run this program is by typing bash before the filename.
Execute the following:
bash sample.sh

Your output should be similar to the following:

7. You can avoid having to type bash in front of the filename by making the file
"executable". Run the following commands:
chmod a+x sample.sh
./sample.sh

Your output should be similar to the following:

9
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

8. A common feature used in scripting is called "backquoting". With this technique,


you can run a shell command "within" another shell command. The outcome of
the internal command is returned as an argument to the external command.
Add the following to the bottom of the sample.sh command and execute it:
echo "Today is" `date +%a`

Now execute the script:


./sample.sh

9. We have been using ./ in front of the sample.sh filename to indicate that the
file is in the current directory. Execute the following to see how the shell would
fail to find the file if we don't use the ./:
sample.sh

Your screen should look like the following:

10
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

10. Recall that the $PATH variable is used to search for commands that you type.
Execute the following to see the $PATH variable for the sysadmin account:
echo $PATH

Your output should be similar to the following:

11. Note that /home/sysadmin/bin is one of the directories in the PATH. This is a
great place to put your shell scripts:
mkdir /home/sysadmin/bin
mv sample.sh /home/sysadmin/bin
sample.sh

Your screen should look like the following:

11
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

12. When a script executes, each command runs using the file access rights of the
person who runs the script. Using a file editor of your choice, create file called
access.sh and add the following to it:
cat /etc/shadow

Now execute the following commands to add execution privileges to that script
and then execute it.
chmod a+x access.sh
./access.sh

Your output should be similar to the following:

Note that the sysadmin account does not have the permission to view the /etc/shadow
file.
While you can create setuid scripts, allowing access to files that the user would not
normally have access to, this is generally not considered a good idea due to security
issues.

12
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Conditional Execution

Note that during this section more complex examples will be demonstrated. When
doing so, we will be using a technique to describe what is happening in the program.
The technique will look like the following:
Enter this column into drive.sh

This column describes the code


(dont enter into the file)

echo Please enter your age


read age

#read user input and place in


#$age variable

When following the instructions provided, you are to enter the bold text from the left
column into the specified file (drive.sh in the example above). The right column is
used to describe specific lines in the program. The pound sign (#) character is used
because in a shell script, you can place comments within your program by using a #
character.
1. More complex scripts may make use of conditional execution. A conditional
expression, like the "if" statement, can make use of the outcome of a command
called "test". The "test" statement compares two numbers (or two strings) for
things like "equal to", "less than", etc.
Create the following file (drive.sh) and make it executable to see how the "if"
and "test" statements work. Begin by placing the following in drive.sh:
Enter this column into drive.sh

This column describes the code


(dont enter into the file)

echo Please enter your age


read age
if test $age lt 16

#read user input and place in


#$age variable
#test $age -lt 16 returns "true" if $age
#is numerically less than 16

then
echo You are not old enough to drive.
else
echo You can drive!
#This ends the if statement

fi

Then make the file executable and run it:


chmod a+x drive.sh
./drive.sh

13
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

Your output should be similar to the following:

Verbally, you could read the "if" statement as "If $age is less than 16, then echo 'You are
not old enough to drive', else echo 'You can drive!'". The "fi" ends the "if" statement.
Note: $age must be an integer value. If not, the program will crash.

14
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

2. The test statement is automatically called when you place its arguments within
square brackets ( [ ] ). Modify the if line of drive.sh so it looks like the
following:
if [ $age -lt 16 ]

Then, run the program again:


./drive.sh

Your output should be similar to the following:

To see a full list of test conditions, run the command man test.

15
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

3. You can also use the outcome of other shell commands as they all return
"success" or "failure". For example, create and run the following program, which
can be used to determine if a user account is on this system. Add the following
to check.sh:
echo "Enter a username to check: "
read name
if grep $name /etc/passwd > /dev/null
then
echo "$name is on this system"
else
echo "$name does not exist"
fi

Then, run the following commands:


chmod a+x check.sh
./check.sh

Your output should be similar to the following:

16
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

4. Another common conditional statement is called the "while" loop. Begin by


placing the following in num.sh:
Enter this column into num.sh

This column describes the code


(dont enter into the file)

echo Please enter a number greater than 100


read num
while [ $num le 100 ]

#Execute code from do to done" if


#test condition is true

do
echo $num is NOT greater than 100.
echo Please enter a number greater than 100
read num
#This ends the done statement

done
echo Finally, $num is greater than 100

Then make the file executable and run it:


chmod a+x num.sh
./num.sh

Your output should be similar to the following:

17
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

If the conditional check for the while statement ($num -le 100) returns true, then the
statements between do and done are executed. Once those statements have
completed executing, the conditional check for the while statement is checked again. If
true, then again the statements between do and done are executed. This is repeated
until the while condition returns false.
5. Scripting code is part of the BASH shell, which means you can use these
statements on the command line just like you use them in a shell script. This can
be useful for a statement like the for statement, a statement that will assign a
list of values one at a time to a variable. This allows you to perform a set of
operations on each value. For example, run the following:
for name in /etc/passwd /etc/hosts /etc/group
do
wc $name
done

Your output should be similar to the following:

Note that the wc command was run three times: once for /etc/passwd, once for
/etc/hosts and once for /etc/group.

18
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

6. Often the seq command is used in conjunction with the for statement. The seq
command can generate a list of integer values, for instance from 1 to 10. For
example, run the following to create 12 files named test1, test2, test3, etc. (up
to test12):
ls
for num in `seq 1 12`
do
touch test$num
done
ls

Your output should be similar to the following:

19
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

7. Sometimes you will want to send a message to a user, like the superuser, when
an event takes place. Create the following program, filecheck.sh, which will
test to make sure the /tmp/check file exists and send the superuser an email
message if it the /tmp/check file does not exist:
if [ -f /tmp/check ]
then
echo "all is well"
else
echo "/tmp/check file is missing"
fi

| mail root

Your output should be similar to the following:

20
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Linux+ Lab Series (LX0-102) Lab 11b: BASH Scripting

8. Make filecheck.sh executable, run the script and verify that it functions
correctly:
chmod a+x filecheck.sh
touch /tmp/check
./filecheck.sh
rm /tmp/check
./filecheck.sh
su - root
netlab123
mail

Your output is similar to the following:

You will see a new message from sysadmin. You can read this message by typing the
message number (the number before sysadmin, 1 in this case) at the & prompt. To quit
the mail utility, type q. Return to the sysadmin account by typing exit.
9. Click the X in the upper-right corner to close the terminal window.
10. Close the Fedora Workstation remote pc window.
11. Click the Im Done button to end the reservation.

21
This work by the National Information Security and Geospatial Technologies Consortium (NISGTC), and except where
otherwise noted, is licensed under the Creative Commons Attribution 3.0 Unported License.

Вам также может понравиться