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
AU$36.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial
Renews at AU$24.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
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
Estimated delivery fee Deliver to Australia

Economy delivery 7 - 10 business days

AU$19.95

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

Economy delivery 7 - 10 business days

AU$19.95

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
AU$24.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
AU$249.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 AU$5 each
Feature tick icon Exclusive print discounts
AU$349.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 AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 281.97
Linux: Powerful Server Administration
AU$137.99
Mastering Python Networking
AU$75.99
Mastering Bash
AU$67.99
Total AU$ 281.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 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