Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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

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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€18.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
€189.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
€264.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 169.97
Linux: Powerful Server Administration
€94.99
Linux Shell Scripting Cookbook
€41.99
Linux Shell Scripting Bootcamp
€32.99
Total 169.97 Stars icon

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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.