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

Arrow left icon
Profile Icon James K Lewis
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Jul 2017 208 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon James K Lewis
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Jul 2017 208 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.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 2. Working with Variables

This chapter will show how variables are used in a Linux system and in scripts.

The topics covered in this chapter are:

  • Using variables in scripts
  • Validating parameters using conditional statements
  • Comparison operators for strings
  • Environment variables

Using variables in scripts

A variable is simply a placeholder for some value. The value can change; however, the variable name will always be the same. Here is a simple example:

   a=1

This assigns the value 1 to variable a. Here's another one:

   b=2

To display what a variable contains use the echo statement:

   echo Variable a is: $a

Note

Notice the $ preceding the variable name. This is required in order to show the contents of the variable.

If at anytime, you aren't seeing the results you expect first check for the $.

Here's an example using the command line:

$ a=1
$ echo a
a
$ echo $a
1
$ b="Jim"
$ echo b
b
$ echo $b
Jim

All variables in a Bash script are considered to be strings. This is different than in a programming language such as C, where everything is strongly typed. In the preceding example, a and b are strings even though they appear to be integers.

Here's a short script to get us started:

Chapter 2 - Script 1

#!/bin/sh
#
# 6/13/2017
#
echo "script1...

Validating parameters using conditional statements

Variables can be tested and compared against other variables when using a variable as a number.

Here is a list of some of the operators that can be used:

Operator

Description

-eq

This stands for equal to

-ne

This stands for not equal to

-gt

This stands for greater than

-lt

This stands for less than

-ge

This stands for greater than or equal to

-le

This stands for less than or equal to

!

This stands for the negation operator

Let's take a look at this in our next example script:

Chapter 2 - Script 2

#!/bin/sh
#
# 6/13/2017
#
echo "script2"

# Numeric variables
a=100
b=100
c=200
d=300

echo a=$a b=$b c=$c d=$d     # display the values

# Conditional tests
if [ $a -eq $b ] ; then
 echo a equals b
fi

if [ $a -ne $b ] ; then
 echo a does not equal b
fi

if [ $a -gt $c ] ; then
 echo a is greater than c
fi

if [ $a -lt $c ] ; then
 echo a is less than c
fi

if [ $a -ge $d ] ; then
 echo a is greater than...

Comparison operators for strings

The comparison for strings are different than for numbers. Here is a partial list:

Operator

Explanation

=

This stands for equal to

!=

This stands for not equal to

>

This stands for greater than

<

This stands for less than

Now let's take a look at Script 3:

Chapter 2 - Script 3

  1  #!/bin/sh
  2  #
  3  # 6/13/2017
  4  #
  5  echo "script3"
  6  
  7  # String variables
  8  str1="Kirk"
  9  str2="Kirk"
 10  str3="Spock"
 11  str3="Dr. McCoy"
 12  str4="Engineer Scott"
 13  str5="A"
 14  str6="B"
 15  
 16  echo str1=$str1 str2=$str2 str3=$str3 str4=$str4
 17  
 18  if [ "$str1" = "$str2" ] ; then
 19   echo str1 equals str2
 20  else
 21   echo str1 does not equal str2
 22  fi
 23  
 24  if [ "$str1" != "$str2" ] ; then
 25   echo str1 does not equal str2
 26  else
 27   echo str1 equals str2
 28  fi
 29  
 30...

Environment variables

So far we have only talked about variables that are local to a script. There are also system wide environment variables (env vars) which play a very important part of any Linux system. Here are a few, some of which the reader may already be aware of:

Variable

Role

HOME

user's home directory

PATH

directories which are searched for commands

PS1

command line prompt

HOSTNAME

hostname of the machine

SHELL

shell that is being used

USER

user of this session

EDITOR

text editor to use for crontab and other programs

HISTSIZE

number of commands that will be shown by the history command

TERM

type of command line terminal that is being used

Most of these are self-explanatory, however, I will mention a few.

The PS1 environment variable controls what the shell prompt displays as part of the command line. The default setting is usually something like [guest1@big1 ~]$, which is not as useful as it could be. At a minimum, a good prompt shows...

Summary

In this chapter we covered how to declare and use both environment and local variables. We talked about how math is performed and how to work with arrays.

We also covered using variables in scripts. Script 1 showed how to assign a variable and display its value. Script 2 showed how to deal with numeric variables and Script 3 showed how to compare strings. Script 4 showed logical operators and Script 5 showed how math can be performed. Script 6 showed how environment variables are used and Script 7 showed how to use arrays.

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
$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 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.