Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
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

eBook
$9.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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

Tip

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.

Who is this book for?

This book is for both GNU/Linux users who want to do amazing things with the shell and for advanced users looking for ways to make their lives with the shell more productive.

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
Estimated delivery fee Deliver to Egypt

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

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

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Egypt

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 198.97
Linux: Powerful Server Administration
$99.99
Linux Shell Scripting Cookbook
$54.99
Linux Shell Scripting Bootcamp
$43.99
Total $ 198.97 Stars icon
Banner background image

Table of Contents

11 Chapters
1. Getting Started with Shell Scripting Chevron down icon Chevron up icon
2. Working with Variables Chevron down icon Chevron up icon
3. Using Loops and the sleep Command Chevron down icon Chevron up icon
4. Creating and Calling Subroutines Chevron down icon Chevron up icon
5. Creating Interactive Scripts Chevron down icon Chevron up icon
6. Automating Tasks with Scripts Chevron down icon Chevron up icon
7. Working with Files Chevron down icon Chevron up icon
8. Working with wget and curl Chevron down icon Chevron up icon
9. Debugging Scripts Chevron down icon Chevron up icon
10. Scripting Best Practices Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 50%
1 star 0%
DreamWeaver Aug 20, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Finally a book that gives you the meat and bones of scripting! An easy and practical read for those who are looking for no nonsense scripting knowledge. Worth every dollar!
Amazon Verified review Amazon
Charles Smiles Jan 20, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
First of all, i've probably purchased 10 bad books on amazon and only left one bad review. Even when they are bad i respect the time an author puts in preparing a book. The author of this book simply does not deserve this kind of respect. Never mind this is a 200 page book, very little effort was put forth to ensure the material was comprehensive and gave readers depth in the material. I actually know how to shell script and have been doing it for my job for years. I purchased this book as a refresher. This author made no effort to explain much of the concepts. I stopped after the first chapter. Granted i understood all 6 basic scripts, but if i had little to no experience i would be completely lost. Can't believe on page 7 he actually typed "The meaning of the remaining lines can be determined by the script itself..." WTF?? No...you explain those lines in your script. That's your job.Like seriously? I actually looked at the intended audience section of the book and made no mention that you had to be an experienced scripter so i really feel for newbies that hit this point only 7 pages into the book and you are lost. I further glanced at other pages in the book and noticed that reoccuring pattern of "here is my script...you figure it out".I've produced technical documentation for mentees at work and under no way would i do this to them.This should be no surprise. Packt publishing has a habit of producing some of the industries worst technical books. They are of low quality. This book is offensive and should be pulled.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela