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
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial

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

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 : 9781784396879
Languages :
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 : Jun 21, 2017
Length: 502 pages
Edition : 1st
Language : English
ISBN-13 : 9781784396879
Languages :
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 zł20 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 zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 823.97
Linux: Powerful Server Administration
zł403.99
Mastering Python Networking
zł221.99
Mastering Bash
zł197.99
Total 823.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

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.