Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering Bash
Mastering Bash

Mastering Bash: A Step-by-Step Guide to working with Bash Programming and Shell Scripting

eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m

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
Table of content icon View table of contents Preview book icon Preview Book

Mastering Bash

Operators

What we have looked at so far is tinkering with values returned from variable expansions and descriptors used in a tricky way. So, something nice, but we could not do much more, since we do not have a way to actually relate values, compare or even modify at our will.

Here is where the operators come in to play, and we will see how to modify the value of a variable so that it will hold a value and, over time, modify to gather new information. So, let's start from something simple, from basic math then move on to something more complex.

One last thing we have to bear in mind before proceeding is that the operators follow an order of precedence:

  • The compound logical operators -a, -o, and && have a low precedence
  • The arithmetic operators have the following precedence:
    • Multiply
    • Divide
    • Add
    • Subtract
  • The evaluation of operators with equal precedence is from...

Arithmetic operators

Arithmetic operators do what you think they do, that is, add, subtract, divide, and so on. It is something we are familiar with even without specific programming knowledge. Let's see each of them and how they can be used to manipulate the value of variables.

Before proceeding, keep in mind that for a shell script, a number is a decimal unless you prefix that with a 0 for the octal, a 0x for a hexadecimal number, or a base#number for a number that evaluates on the base.

The + operator

This is like what we see at primary school; this operator allows us to add an integer to the value of the variable, as we can see in the following example:

#!/bin/bash
echo "Hello user, please give me a number: &quot...

Assignment operators

We have seen how to manipulate the value assigned to a variable and an integer so far, and then reassign this value to another variable or the same one. But why use two operations when you can alter the value of a variable and reassign it at the same time using the assignment operators?

The += operator

This operator adds a quantity to the value of the variable and assigns the outcome to the variable itself, but to clarify its use, let's rewrite one of the examples we've seen before:

#!/bin/bash    
echo "Hello user, please give me a number: "
read user_input
echo "And now another one, please: "

Adding

echo "The user_input variable value is: ${user_input}"
echo...

Bitwise operators

Bitwise operators are useful when dealing with bit masks, but in normal practice, they are not so easy to use, and so you will not encounter them very often. However, since they are available in Bash we are going to have a look at them with some examples.

Left shift (<<)

The bitwise left shift operators simply multiplies by 2 a value for each shift position; the following example will make everything more clear:

zarrelli:~$ x=10 ; echo $((x<<1))
20
zarrelli:~$ x=10 ; echo $((x<<2))
40
zarrelli:~$ x=10 ; echo $((x<<3))
80
zarrelli:~$ x=10 ; echo $((x<<4))
160

What happened? As we said before, the bitwise operators work on a bit mask, so let's start converting the integer 10 to...

Logical operators

Here, we come to something really useful for our scripts, a bunch of operators that will enable us to perform some tests and react as a consequence. So, we will be able to make our script react to a some change or user input and be more flexible. Let's see what is available.

Logical NOT (!)

The NOT operator is used to test whether an expression is true and holds true when the expression is false:

[! expression ]  

Let's go back to one of our previous scripts and make it more user-friendly:

#!/bin/bash    
echo "Hello user, please give me a number between 10 and 12: "
read user_input
if [ ! ${user_input} -eq11 ]
then
echo "The number ${user_input} is not what we are looking for...

Comma operator (,)

One last operator that actually does not fit into any other category is the comma operator, which is used to chain together arithmetic operations. All the operations are evaluated, but only the value from the last one is returned:

zarrelli:~$ echo $((x=1, 7-2))
5
zarrelli@moveaway:~$ echo ${x}
1

Operators evaluation order and precedence in decreasing relevance

Operators are evaluated in a precise order and we must keep this in mind when working with them. It is not so easy to remember what is evaluated before and what after, so the following table will help us to keep in mind the order and precedence of operators:

Operator

Evaluation order

++ --

Unary operators for incrementing/decrementing, evaluated from left to right

+- !~

Unary plus and minus, evaluated from right to left

* / %

Multiplication, division, modulo, are evaluated from left to right and are evaluated after

+ -

Addition and subtraction are evaluated from left to right

<<>>

Bitwise shift are evaluated from left to right

<= =><>

Comparison operators, from left to right

== !=

Equality operators, from left to right

&

Bitwise AND...

Exit codes

We have already seen that when a program encounters issues it exits, usually with an error message. What does exits means? Simply that the code execution terminates and the program, or the script, returns an exit code that informs the system of what happened. This is very handy for us, since we can trap the exit code of a program and decide what to do based on its value.

0

Success

1

Failure

2

Misuse of builtin

126

Command not executable

127

Command not found

128

Invalid argument

128+x

Fatal error exit with signal x

130

Execution terminated by Ctrl +C

255

Exit state out of boundary (0-255)

So, maybe you already guessed, each execution terminates with an exit code, whether successful or not, with an error message or silently:

zarrelli:~$ date ; echo $?
Thu 2 Feb 19:17:48 GMT 2017
0

As you can see, the exit code...

Summary

In the previous chapter, we had a look at the variable; now we have just looked at how to correlate them. Assigning values and being able to perform some math or logic operations on them gives us more flexibility, since we do not just collect something, but transform it into something different and new. We also learned that exit codes can sometimes be pitfalls, trapping us with red herrings, and this tells us something important: never take anything as a given, always double-check what you are writing in your code, and always try to catch all the possible outcomes and exceptions. It seems like something obvious, but being such common sense, we tend to overlook this simple but effective code style advice.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • From roots to leaves, learn how to program in Bash and automate daily tasks, pouring some spice in your scripts
  • Daemonize a script and make a real service of it, ensuring it’s available at any time to process user-fed data or commands
  • This book provides functional examples that show you practical applications of commands

Description

System administration is an everyday effort that involves a lot of tedious tasks, and devious pits. Knowing your environment is the key to unleashing the most powerful solution that will make your life easy as an administrator, and show you the path to new heights. Bash is your Swiss army knife to set up your working or home environment as you want, when you want. This book will enable you to customize your system step by step, making your own real, virtual, home out of it. The journey will take you swiftly through the basis of the shell programming in Bash to more interesting and challenging tasks. You will be introduced to one of the most famous open source monitoring systems—Nagios, and write complex programs with it in any languages. You’ll see how to perform checks on your sites and applications. Moving on, you’ll discover how to write your own daemons so you can create your services and take advantage of inter-process communication to let your scripts talk to each other. So, despite these being everyday tasks, you’ll have a lot of fun on the way. By the end of the book, you will have gained advanced knowledge of Bash that will help you automate routine tasks and manage your systems.

Who is this book for?

If you're a power user or system administrator involved in writing Bash scripts to automate tasks, then this book is for you. This book is also ideal for advanced users who are engaged in complex daily tasks.

What you will learn

  • Understand Bash right from the basics and progress to an advanced level
  • Customise your environment and automate system routine tasks
  • Write structured scripts and create a command-line interface for your scripts
  • Understand arrays, menus, and functions
  • Securely execute remote commands using ssh
  • Write Nagios plugins to automate your infrastructure checks
  • Interact with web services, and a Slack notification script
  • Find out how to execute subshells and take advantage of parallelism
  • Explore inter-process communication and write your own daemon

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 21, 2017
Length: 502 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391980
Languages :

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

Product Details

Publication date : Jun 21, 2017
Length: 502 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391980
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.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
£169.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
£234.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 £ 161.97
Linux: Powerful Server Administration
£82.99
Mastering Python Networking
£41.99
Mastering Bash
£36.99
Total £ 161.97 Stars icon

Table of Contents

14 Chapters
Let's Start Programming Chevron down icon Chevron up icon
Operators Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
Quoting and Escaping Chevron down icon Chevron up icon
Menus, Arrays, and Functions Chevron down icon Chevron up icon
Iterations Chevron down icon Chevron up icon
Plug into the Real World Chevron down icon Chevron up icon
We Want to Chat Chevron down icon Chevron up icon
Subshells, Signals, and Job Controls Chevron down icon Chevron up icon
Lets Make a Process Chat Chevron down icon Chevron up icon
Living as a Daemon Chevron down icon Chevron up icon
Remote Connections over SSH Chevron down icon Chevron up icon
Its Time for a Timer Chevron down icon Chevron up icon
Time for Safety 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.8
(4 Ratings)
5 star 50%
4 star 0%
3 star 25%
2 star 25%
1 star 0%
Dragon Nov 18, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A lot of information. Very well put together, now I have to apply what I've learned , I have a lot of highlighted parts I keep for reference, great book !!! I would recommend it to any one with a computer
Amazon Verified review Amazon
skeptic Aug 17, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The books is about scripting in bash, which makes is a welcome addition of "bash bookshelf" of system administrators. Only very few books are concentrated on this topic. And it provides some pretty elaborate, practical examples of programs in bash language.It consists of two parts: overview of the language and a set chapters devoted to selected topics.Overview of the "Bash language" provided in the Part I of the book is so-so. It does not cover modern capabilities of Bash 4.2 and later well, although some information provided is valuable for Unix sysadmins. But multiple other, better books exists on this topic.But some chapters in Part II of the book are really interesting and contain valuable information. Two of them really stand out:1. A chapter on how to writs a simple Nagios probes. It is written well and allow you immediately write you own simple probe. which for any sysadmin alone justifies the price of the book.2. The second chapter which strikes me as very useful is based on pretty slick idea that you can reuse some chat services for monitoring of your infrastructure. This is probably unacceptable for multinationals, but might be very useful for cash strapped start-ups and non-profits.The author uses Slack messaging service as an example of service that can be used this way. Slack has so called Webhooks that you can use for sending messages via HTTP put:== quote ==Slack has some endpoints, sensitive URLs; and when you post something through HTTP to endpoints, you actually communicate with Slack. What makes these WebHook interesting is that they are stateless, since they do not rely on a continuously open connection to the service; and you just ping Slack whenever you need to post or retrieve some pieces of information. Slack supports two different kinds of WebHooks...== end of quote ==As for any book from this publisher (Packt Publishing ), if you buy paper version of the book you are eligible to get ebook which is another important plus. We need to support publishers that use this, more modern, method of book production and distribution.== end of quote ==
Amazon Verified review Amazon
Gregory Levin Apr 03, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Easy book for shell
Amazon Verified review Amazon
Decano Feb 10, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I have been writing shell scripts "since the beginning", but things have changed. Bash, in particular, has evolved (in a very positive way) over the years, and is a far cry from the old sh and csh. The more recent versions (bash 3.x and 4.x) have features that are new to those of us who are "old timers". Yes, I could look up the new features on the Net, but I wanted a "real book" that I could (a) browse through to see what I am missing and (b) use as a desktop reference.Unfortunately this is not an acceptable book, or at least is not acceptable to me.A short list of defects:Examples, even of very simple concepts, are poorly written. The author seems to hide the one relevant line in a dozen or more lines of completely unrelated cruft. I could figure it all out, since I am not a "bash newbie". But it was wasting my time. And for a newcomer, I am afraid that they would just get lost.Attempts to be "cute", like the obscured examples, were just wasting my time. Move on.Finally, I found some of the grammar questionable, but that is so subjective that I will just say that the author's style is not mine!I'll look for a better book.
Amazon Verified review Amazon
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.