Book Image

Bash Cookbook

By : Ron Brash, Ganesh Sanjiv Naik
Book Image

Bash Cookbook

By: Ron Brash, Ganesh Sanjiv Naik

Overview of this book

In Linux, one of the most commonly used and most powerful tools is the Bash shell. With its collection of engaging recipes, Bash Cookbook takes you through a series of exercises designed to teach you how to effectively use the Bash shell in order to create and execute your own scripts. The book starts by introducing you to the basics of using the Bash shell, also teaching you the fundamentals of generating any input from a command. With the help of a number of exercises, you will get to grips with the automation of daily tasks for sysadmins and power users. Once you have a hands-on understanding of the subject, you will move on to exploring more advanced projects that can solve real-world problems comprehensively on a Linux system. In addition to this, you will discover projects such as creating an application with a menu, beginning scripts on startup, parsing and displaying human-readable information, and executing remote commands with authentication using self-generated Secure Shell (SSH) keys. By the end of this book, you will have gained significant experience of solving real-world problems, from automating routine tasks to managing your systems and creating your own scripts.
Table of Contents (15 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Preface

In this book, we are writing a variety of scripts using Bash, or the Bourne Again Shell. They range from simple to more complex and handy utilities or programs. Currently, Bash is the default shell used by most GNU/Linux distributions and is used ubiquitously within the Linux Terminal. It can be used for any number of tasks and is flexible across the Linux/Unix ecosystem. In other words, a user familiar with Bash and the Linux CLI can install it themselves on almost any other Linux system and perform similar tasks with a negligible amount of alterations (if any are required at all). Bash scripts can also still work with few dependencies on other software installed, and on a very lean system (minimal installation), a user can still write a powerful script to automate tasks or assist with repeated task execution.

This cookbook focuses entirely on Bash usage in an Ubuntu environment, a very common Linux distribution, but it should be portable to other distributions with relative ease. This book is not written for direct usage on Apple or Windows OSes even though it is possible to port elements over to them.

Who this book is for

Bash Cookbook is for power users or system administrators who are involved in writing Bash scripts in order to automate tasks or are aiming to enhance their productivity on the command line. For example, instead of remembering a series of commands to perform a specific operation, all of those commands can be put into a single script dedicated to that task, and they can perform input validation and format output. Why not save time and reduce errors through a powerful tool?

This book is also ideal if you are interested in learning how to automate complex daily system tasks that can be executed by various system infrastructure such as starting a script on system boot, or through scheduled cron jobs.

 

 

What this book covers

Chapter 1Crash Course in Bash, covers the Linux shell/Bash to get you up and running, and the remainder of the book will just fall into place.

Chapter 2, Acting Like a Typewriter and File Explorer, introduces several bolt-on technologies to make Bash even more extensive when searching for items and text, or automating file explorer/filesystem operations. 

Chapter 3, Understanding and Gaining File System Mastery, will help you view files from various angles: head, tail, less, searching for files by name and/or extension, creating a diff of two files, patching, creating symbolic links and using them effectively, crawling filesystem directories, printing a tree, and more.

Chapter 4, Making a Script Behave Like a Daemon, is about creating components that mimic application functionality, such as menus or a daemon.

Chapter 5, Scripts for System Administration Tasks, introduces logs, archiving them, job/task management, network connectivity, securing systems using a firewall (iptables), monitoring directories for changes, and creating users.

Chapter 6, Scripts for Power Users, is about creating syslog entries using the logger command, taking backups, creating graphics and presentations on the CLI, checking file integrity and tampering, mounting network filesystems, retrieving files, browsing the Web, capturing network traffic, finding binary dependencies, and encrypting and decrypting a file.

Chapter 7, Writing Bash to Win and Profit, will help you learn how to use commands and scripts for many tasks. You will get an idea about writing bash scripts for monitoring certain tasks. 

Chapter 8, Advanced Scripting Techniques, will help you learn about advanced scripting techniques as well as how to customize their shell.

To get the most out of this book

As the authors, we wrote this book to be accessible and teach you, the reader many different approaches to programming with Bash through several recipes. However, to get the most out of them, we encourage you to:

  • Have a Linux system setup and configured (ideally Ubuntu) to complete the recipes
  • Work through the recipes 
  • Keep in mind what the components of each recipe and even the recipes themselves to see how they could be reused or combined in new ways

However,  this book assumes a certain level of knowledge to begin your journey and these skills will not be covered in this book. These skills include the following:

  • How to setup and configure a Linux system
  • How to install, access, and configure a specific text editor (although several are already included in most Linux distributions)
  • Some basics about computing and programming (although we will do our best to provide a crash course)

To gain proficiency in those areas, we recommend that you either give it your best shot if you are an adept problem solver and quick learner, or checkout the following resources first:

  • Linux or distribution communities
  • Open source forums or groups
  • YouTube or similar media

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

 

 

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Bash-Cookbook. In case, there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The full path is more concrete and hardcoded; the interpreter will try to use the complete path. For example, /bin/ls or /usr/local/bin/myBinary.."

A block of code is set as follows:

#!/bin/bash
AGE=17
if [ ${AGE} -lt 18 ]; then
    echo "You must be 18 or older to see this movie"
fi

 

Any command-line input or output is written as follows:

rbrash@moon:~$ history
1002 ls
1003 cd ../
1004 pwd
1005 whoami
1006 history

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this.

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it...

This section contains the steps required to follow the recipe.

How it works...

This section usually consists of a detailed explanation of what happened in the previous section.

 

There's more...

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

 

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.