Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Linux Shell Scripting Bootcamp
Linux Shell Scripting Bootcamp

Linux Shell Scripting Bootcamp: The fastest way to learn Linux shell scripting

By James K Lewis
$35.99 $24.99
Book Jul 2017 208 pages 1st Edition
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jul 19, 2017
Length 208 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781787281103
Vendor :
Red Hat
Table of content icon View table of contents Preview book icon Preview Book

Linux Shell Scripting Bootcamp

Chapter 1. Getting Started with Shell Scripting

This chapter is a brief introduction to shell scripting. It will assume the reader is mostly familiar with script basics and will serve as a refresher.

The topics covered in this chapter are as follows:

  • The general format of a script.

  • How to make a file executable.

  • Creating a good Usage message and handling return codes.

  • Show how to pass parameters from the command line.

  • Show how to validate parameters by using conditional statements.

  • Explain how to determine the attributes of files.

Getting started


You will always be able to create these scripts under a guest account, and most will run from there. It will be clearly stated when root access is needed to run a particular script.

The book will assume that the user has put a (.) at the beginning of the path for that account. If not, to run a script prepend ./ to the filename. For example:

 $ ./runme

The scripts will be made executable using the chmod command.

It is suggested that the user create a directory under his guest account specifically for the examples in this book. For example, something like this works well:

$ /home/guest1/LinuxScriptingBook/chapters/chap1

Of course, feel free to use whatever works best for you.

Following the general format of a bash script the very first line will contain this and nothing else:

#!/bin/sh

Note that in every other case text following the # sign is treated as comments.

For example,

# This entire line is a comment

chmod 755 filename   # This text after the # is a comment

Use comments however you deem appropriate. Some people comment every line, some don't comment anything. I try to strike a balance somewhere in the middle of those two extremes.

Using a good text editor

I have found that most people are comfortable using vi to create and edit text documents under a UNIX/Linux environment. This is fine as vi is a very dependable application. I would suggest not using any type of word processing program, even if it claims to have a code development option. These programs might still put invisible control characters in the file which will probably cause the script to fail. This can take hours or even days to figure out unless you are good at looking at binary files.

Also, in my opinion, if you plan to do a lot of script and/or code development I suggest looking at some other text editor other than vi. You will almost certainly become more productive.

Demonstrating the use of scripts


Here is an example of a very simple script. It might not look like much but this is the basis for every script:

Chapter 1 - Script 1

#!/bin/sh
#
#  03/27/2017
#
exit 0

Note

By convention, in this book the script lines will usually be numbered. This is for teaching purposes only, in an actual script the lines are not numbered.

Here is the same script with the lines numbered:

1  #!/bin/sh
2  #
3  # 03/27/2017
4  #
5  exit 0
6

Here is an explanation for each line:

  • Line 1 tells the operating system which shell interpreter to use. Note that on some distributions /bin/sh is actually a symbolic link to the interpreter.

  • Lines that begin with a # are comments. Also, anything after a # is also treated as a comment.

  • It is good practice to include a date in your scripts, either here in the comments section and/or in the Usage section (covered next).

  • Line 5 is the return code from this script. This is optional but highly recommended.

  • Line 6 is a blank line and is the last line of the script.

Using your favorite text editor, edit a new file named script1 and copy the preceding script without the line numbers into it. Save the file.

To make the file into an executable script run this:

$ chmod 755 script1

Now run the script:

$ script1

If you did not prepend a . to your path as mentioned in the introduction then run:

$ ./script1

Now check the return code:

$ echo $?
0

Here is a script that does something a little more useful:

Chapter 1 - Script 2

#!/bin/sh
#
# 3/26/2017
#
ping -c 1 google.com        # ping google.com just 1 time
echo Return code: $?

The ping command returns a zero on success and non-zero on failure. As you can see, echoing $? shows the return value of the command preceding it. More on this later.

Now let's pass a parameter and include a Usage statement:

Chapter 1 - Script 3

  1  #!/bin/sh
  2  #
  3  # 6/13/2017
  4  #
  5  if [ $# -ne 1 ] ; then
  6   echo "Usage: script3 file"
  7   echo " Will determine if the file exists."
  8   exit 255
  9  fi
 10  
 11  if [ -f $1 ] ; then
 12   echo File $1 exists.
 13   exit 0
 14  else
 15   echo File $1 does not exist.
 16   exit 1
 17  fi
 18  

Here is an explanation for each line:

  • Line 5 checks to see if a parameter was given. If not, lines 6 through 9 are executed. Note that is it usually a good idea to include an informative Usage statement in your script. It is also good to provide a meaningful return code.

  • Line 11 checks to see if the file exists and if so lines 12-13 are executed. Otherwise lines 14-17 are run.

  • A word about return codes: It is standard practice under Linux/UNIX to return zero if the command was successful, and non-zero if not. In this way the code returned can mean something useful, not only to humans, but to other scripts and programs as well. However, it is not mandatory to do this. If you want your script to return codes that are not errors but indicate some other condition by all means do so.

This next script expands on this topic:

Chapter 1 - Script 4

  1  #!/bin/sh
  2  #
  3  # 6/13/2017
  4  #
  5  if [ $# -ne 1 ] ; then
  6   echo "Usage: script4 filename"
  7   echo " Will show various attributes of the file given."
  8   exit 255
  9  fi
 10  
 11  echo -n "$1 "                # Stay on the line
 12  
 13  if [ ! -e $1 ] ; then
 14   echo does not exist.
 15   exit 1                      # Leave script now
 16  fi
 17  
 18  if [ -f $1 ] ; then
 19   echo is a file.
 20  elif [ -d $1 ] ; then
 21   echo is a directory.
 22  fi
 23  
 24  if [ -x $1 ] ; then
 25   echo Is executable.
 26  fi
 27  
 28  if [ -r $1 ] ; then
 29   echo Is readable.
 30  else
 31   echo Is not readable.
 32  fi
 33  
 34  if [ -w $1 ] ; then
 35   echo Is writable.
 36  fi
 37  
 38  if [ -s $1 ] ; then
 39   echo Is not empty.
 40  else
 41   echo Is empty.
 42  fi
 43  
 44  exit 0                       # No error
 45  

Here is an explanation for each line:

  • Lines 5-9: If the script is not run with a parameter display the Usage message and exit with a return code of 255.

  • Line 11 shows how to echo a string of text but still stay on the line (no linefeed).

  • Line 13 shows how to determine if the parameter given is an existing file.

  • Line 15 leaves the script as there is no reason to continue if the file doesn't exist.

The meaning of the remaining lines can be determined by the script itself. Note that there are many other checks that can be performed on a file, these are just a few.

Here are some examples of running script4 on my system:

guest1 $ script4
Usage: script4 filename
 Will show various attributes of the file given.

guest1 $ script4 /tmp
/tmp is a directory.
Is executable.
Is readable.
Is writable.
Is not empty.

guest1 $ script4 script4.numbered
script4.numbered is a file.
Is readable.
Is not empty.

guest1 $ script4 /usr
/usr is a directory.
Is executable.
Is readable.
Is not empty.

guest1 $ script4 empty1
empty1 is a file.
Is readable.
Is writable.
Is empty.

guest1 $ script4 empty-noread
empty-noread is a file.
Is not readable.
Is empty.

This next script shows how to determine the number of parameters that were passed to it:

Chapter 1 - Script 5

#!/bin/sh
#
# 3/27/2017
#
echo The number of parameters is: $#
exit 0

Let's try a few examples:

guest1 $ script5
The number of parameters is: 0

guest1 $ script5 parm1
The number of parameters is: 1

guest1 $ script5 parm1 Hello
The number of parameters is: 2

guest1 $ script5 parm1 Hello 15
The number of parameters is: 3

guest1 $ script5 parm1 Hello 15 "A string"
The number of parameters is: 4

guest1 $ script5 parm1 Hello 15 "A string" lastone
The number of parameters is: 5

Note

Remember that a quoted string is counted as 1 parameter. This is a way to pass strings that contain blank characters.

This next script shows how to handle multiple parameters in more detail:

Chapter 1 - Script 6

#!/bin/sh
#
# 3/27/2017
#

if [ $# -ne 3 ] ; then
 echo "Usage: script6 parm1 parm2 parm3"
 echo " Please enter 3 parameters."

 exit 255
fi

echo Parameter 1: $1
echo Parameter 2: $2
echo Parameter 3: $3

exit 0

The lines of this script were not numbered as it is rather simple. The $# contains the number of parameters that were passed to the script.

Summary


In this chapter we looked at the basics of script design. How to make a script executable was shown as was creating an informative Usage message. The importance of return codes was also covered as was the use and validation of parameters.

The next chapter will go into more detail about variables and conditional statements.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand expressions and variables and how to use them practically
  • Familiarize yourself with the various text filtering tools available in Linux
  • A fast-paced and concise guide that gets you well versed with linux shell scripting.

Description

Linux Shell Scripting Bootcamp is all about learning the essentials of script creation, validating parameters, and checking for the existence of files and other items needed by the script. We will use scripts to explore iterative operations using loops and learn different types of loop statements, with their differences. Along with this, we will also create a numbered backup script for backup files. Further, you will get well-versed with how variables work on a Linux system and how they relate to scripts. You’ll also learn how to create and call subroutines in a script and create interactive scripts. The most important archive commands, zip and tar, are also discussed for performing backups. Later, you will dive deeper by understanding the use of wget and curl scripts and the use of checksum and file encryption in further chapters. Finally, you will learn how to debug scripts and scripting best practices that will enable you to write a great code every time! By the end of the book, you will be able to write shell scripts that can dig data from the web and process it efficiently.

What you will learn

[*]Get acquainted with the basics of a shell script to serve as a refresher for more advanced topics [*]Learn different ways to create and run a script [*]Discuss the passing and verification of parameters, along with the verification of other items. [*]Understand the different forms of conditions and loops, and go over the sleep command in detail [*]Learn about different ways to handle the reporting of return codes [*]Create an interactive script by reading the keyboard and use subroutines and interrupts [*]Create scripts to perform backups and go over the use of encryption tools and checksums [*]Use wget and curl in scripts to get data directly from the Internet

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jul 19, 2017
Length 208 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781787281103
Vendor :
Red Hat

Table of Contents

19 Chapters
Linux Shell Scripting Bootcamp Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
Acknowledgement Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Customer Feedback Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started with Shell Scripting Chevron down icon Chevron up icon
Working with Variables Chevron down icon Chevron up icon
Using Loops and the sleep Command Chevron down icon Chevron up icon
Creating and Calling Subroutines Chevron down icon Chevron up icon
Creating Interactive Scripts Chevron down icon Chevron up icon
Automating Tasks with Scripts Chevron down icon Chevron up icon
Working with Files Chevron down icon Chevron up icon
Working with wget and curl Chevron down icon Chevron up icon
Debugging Scripts Chevron down icon Chevron up icon
Scripting Best Practices Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.