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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Linux Shell Scripting Cookbook
Linux Shell Scripting Cookbook

Linux Shell Scripting Cookbook: Do amazing things with the shell and automate tedious tasks , Third Edition

Arrow left icon
Profile Icon Clif Flynt Profile Icon Sarath Lakshman Profile Icon Shantanu Tushar
Arrow right icon
zł59.99 zł177.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook May 2017 552 pages 3rd Edition
eBook
zł59.99 zł177.99
Paperback
zł221.99
Subscription
Free Trial
Arrow left icon
Profile Icon Clif Flynt Profile Icon Sarath Lakshman Profile Icon Shantanu Tushar
Arrow right icon
zł59.99 zł177.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook May 2017 552 pages 3rd Edition
eBook
zł59.99 zł177.99
Paperback
zł221.99
Subscription
Free Trial
eBook
zł59.99 zł177.99
Paperback
zł221.99
Subscription
Free Trial

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Linux Shell Scripting Cookbook

Have a Good Command

In this chapter, we will cover the following recipes:

  • Concatenating with cat
  • Recording and playing back terminal sessions
  • Finding files and file listing
  • Playing with xargs
  • Translating with tr
  • Checksum and verification
  • Cryptographic tools and hashes
  • Sorting unique and duplicate lines
  • Temporary file naming and random numbers
  • Splitting files and data
  • Slicing filenames based on extensions  
  • Renaming and moving files in bulk
  • Spell–checking and dictionary manipulation   
  • Automating interactive input
  • Making commands quicker by running parallel processes
  • Examining a directory, files and subdirectories in it

Introduction

Unix-like systems have the best command-line tools. Each command performs a simple function to make our work easier. These simple functions can be combined with other commands to solve complex problems. Combining simple commands is an art; you will get better at it as you practice and gain experience. This chapter introduces some of the most interesting and useful commands, including grep, awk, sed, and find.

Concatenating with cat

The cat command displays or concatenates the contents of a file, but cat is capable of more. For example, cat can combine standard input data with data from a file. One way of combining the stdin data with file data is to redirect stdin to a file and then append two files. The cat command can do this in a single invocation. The next recipes show basic and advanced usages of cat.

How to do it...

The cat command is a simple and frequently used command and it stands for conCATenate.

The general syntax of cat for reading contents is as follows:

$ cat file1 file2 file3 ...

This command concatenates data from the files specified as command-line arguments and sends that data to stdout.

  • To print contents of a single file, execute the following command...

Recording and playing back terminal sessions

Recording a screen session as a video is useful, but a video is an overkill for debugging terminal sessions or providing a shell tutorial.

The shell provides another option. The script command records your keystrokes and the timing of keystrokes as you type, and saves your input and the resulting output in a pair of files. The scriptreplay command will replay the session.

Getting ready

The script and scriptreplay commands are available in most GNU/Linux distributions. You can create tutorials of command-line hacks and tricks by recording the terminal sessions. You can also share the recorded files for others to playback and see how to perform a particular task with the command line. You can even invoke other interpreters...

Finding files and file listing

The find command is one of the great utilities in the Unix/Linux command-line toolbox. It is useful both at the command line and in shell scripts. Like cat and ls, find has many features, and most people do not use it to its fullest. This recipe deals with some common ways to utilize find to locate files.

Getting ready

The find command uses the following strategy:  find descends through a hierarchy of files, matches files that meet the specified criteria, and performs some actions. The default action is to print the names of files and folders, which can be specified with the -print option.

How to do it...

...

Playing with xargs

Unix commands accept data either from the standard input (stdin) or as command line arguments. Previous examples have shown how to pass data from one application's standard output to another's standard input with a pipe.

We can invoke applications that accept command-line arguments in other ways. The simplest is to use the back-tic symbol to run a command and use its output as a command line:

$ gcc `find '*.c'`

This solution works fine in many situations, but if there are a lot of files to be processed, you'll see the dreaded Argument list too long error message. The xargs program solves this problem.

The xargs command reads a list of arguments from stdin and executes a command using these arguments in the command line. The xargs command can also convert any one-line or multiple-line text inputs into other formats, such as multiple lines (specified number of columns)...

Translating with tr

The tr command is a versatile tool in the Unix command–warrior's kit. It is used to craft elegant one-liner commands. It performs substitution of characters, deletes selected characters, and can squeeze repeated characters from the standard input. Tr is short for translate, since it translates a set of characters to another set. In this recipe, we will see how to use tr to perform basic translation between sets.

Getting ready

The tr command accepts input through stdin (standard input) and cannot accept input through command-line arguments. It has this invocation format:

tr [options] set1 set2

Input characters from stdin are mapped from the first character in set1 to the first character in set2, and so on and the output is...

Checksum and verification

Checksum programs are used to generate a relatively small unique key from files. We can recalculate the key to confirm that a file has not changed. Files may be modified deliberately (adding a new user changes the password file), accidentally (a data read error from a CD-ROM drive), or maliciously (a virus is inserted). Checksums let us verify that a file contains the data we expect it to.

Checksums are used by backup applications to check whether a file has been modified and needs to be backed up.

Most software distributions also have a checksum file available. Even robust protocols such as TCP can allow a file to be modified in transit. Hence, we need to know whether the received file is the original one or not by applying some kind of test.

By comparing the checksum of the file we downloaded with the checksum calculated by the distributer, we can verify that the received file is...

Cryptographic tools and hashes

Encryption techniques are used to protect data from unauthorized access. Unlike the checksum algorithms we just discussed, encryption programs can reconstruct the original data with no loss. There are many algorithms available and we will discuss those most commonly used in the Linux/Unix world.

How to do it...

Let's see how to use tools such as crypt, gpg, and base64:

  • The crypt command is not commonly installed on Linux systems. It's a simple and relatively insecure cryptographic utility that accepts input from stdin, requests a passphrase, and sends encrypted output to stdout:
        $ crypt <input_file >output_file
        Enter passphrase:

We can provide a passphrase on the command line:

        $ crypt...

Sorting unique and duplicate lines

Sorting text files is a common task. The sort command sorts text files and stdin. It can be coupled with other commands to produce the required output. uniq is often used with sort to extract unique (or duplicate) lines. The following recipes illustrate some sort and uniq use cases.

Getting ready

The sort and uniq commands accept input as filenames or from stdin (standard input) and output the result by writing to stdout.

How to do it...

  1. We can sort a set of files (for example, file1.txt and file2.txt), like this:
        $ sort file1.txt file2.txt > sorted.txt

 Alternatively...

Temporary file naming and random numbers

Shell scripts often need to store temporary data. The most suitable location to do this is /tmp (which will be cleaned out by the system on reboot). There are two methods to generate standard filenames for temporary data.

How to do it...

The mktemp command will create a unique temporary file or folder name:

  1. Create a temporary file:
        $ filename=`mktemp`
        $ echo $filename
        /tmp/tmp.8xvhkjF5fH

This creates a temporary file, stores the name in filename, and then displays the name.

  1. Create a temporary directory:
        $ dirname=`mktemp -d`
        $ echo $dirname
        tmp.NI8xzW7VRX

This creates a temporary directory, stores the name in filename, and displays the name.

  • To generate a filename without...

Splitting files and data

Splitting a large file into smaller pieces is sometimes necessary. Long ago, we had to split files to transport large datasets on floppy disks. Today, we split files for readability, for generating logs, or for working around size-restrictions on e-mail attachments. These recipes will demonstrate ways of splitting files in different chunks.

How to do it...

The split command was created to split files. It accepts a filename as an argument and creates a set of smaller files in which the first part of the original file is in the alphabetically first new file, the next set in the alphabetically next file, and so on.

For example, a 100 KB file can be divided into smaller files of 10k each by specifying the split size. The split command supports...

Slicing filenames based on extensions

Many shell scripts perform actions that involve modifying filenames. They may need to rename the files and preserve the extension, or convert files from one format to another and change the extension, while preserving the name, extracting a portion of the filename, and so on.

The shell has built-in features for manipulating filenames.

How to do it...

The % operator will extract the name from name.extension. This example extracts sample from sample.jpg:

file_jpg="sample.jpg" 
name=${file_jpg%.*} 
echo File name is: $name 

The output is this:

File name is: sample

The # operator will extract the extension:

Extract .jpg from the filename stored in the file_jpg variable:

extension=${file_jpg#*.} 
echo Extension is...

Renaming and moving files in bulk

We frequently need to move and perhaps rename a set of files. System housekeeping often requires moving files with a common prefix or file type to a new folder. Images downloaded from a camera may need to be renamed and sorted. Music, video, and e-mail files all need to be reorganized eventually.

There are custom applications for many of these operations, but we can write our own custom scripts to do it our way.

Let's see how to write scripts to perform these kinds of operation.

Getting ready

The rename command changes filenames using Perl regular expressions. By combining the find, rename, and mv commands, we can perform a lot of things.

...

Spell–checking and dictionary manipulation

Most Linux distributions include a dictionary file. However, very few people are aware of this, thus spelling errors abound. The aspell command-line utility is a spell checker. Let's go through a few scripts that make use of the dictionary file and the spell checker.

How to do it...

The /usr/share/dict/ directory contains one or perhaps more dictionary files, which are text files with a list of words. We can use this list to check whether a word is a dictionary word or not:

$ ls /usr/share/dict/ 
american-english  british-english

To check whether the given word is a dictionary word, use the following script:

#!/bin/bash 
#Filename: checkword.sh 
word=$1 
grep "^$1$" /usr/share/dict/british-english...

Automating interactive input

We looked at commands that accept arguments on the command line. Linux also supports many interactive applications ranging from passwd to ssh.

We can create our own interactive shell scripts. It's easier for casual users to interact with a set of prompts rather than remember command line flags and the proper order. For instance, a script to back up a user's work, but not to back up and lock files, might look like this:

$ backupWork.sh
  • What folder should be backed up? notes
  • What type of files should be backed up? .docx

Automating interactive applications can save you time when you need to rerun the same application and frustration while you're developing one.

Getting ready

The first step to automating a task...

Making commands quicker by running parallel processes

Computing power constantly increases not only because processors have higher clock cycles but also because they have multiple cores. This means that in a single hardware processor there are multiple logical processors. It's like having several computers, instead of just one.

However, multiple cores are useless unless the software makes use of them. For example, a program that does huge calculations may only run on one core while the others will sit idle. The software has to be aware and take advantage of the multiple cores if we want it to be faster.

In this recipe, we will see how we can make our commands run faster.

How to do it...

Let's take an example of the md5sum command we discussed in the previous...

Examining a directory, files and subdirectories in it

One of the commonest problems we deal with is finding misplaced files and sorting out mangled file hierarchies. This section will discuss tricks for examining a portion of the filesystem and presenting the contents.

Getting ready

The find command and loops we discussed give us tools to examine and report details in a directory and its contents.

How to do it...

The next recipes show two ways to examine a directory. First we'll display the hierarchy as a tree, then we'll see how to generate a summary of files and folders under a directory.

...
Left arrow icon Right arrow icon

Key benefits

  • Become an expert in creating powerful shell scripts and explore the full possibilities of the shell
  • Automate any administrative task you could imagine, with shell scripts
  • Packed with easy-to-follow recipes on new features on Linux, particularly, Debian-based, to help you accomplish even the most complex tasks with ease

Description

The shell is the most powerful tool your computer provides. Despite having it at their fingertips, many users are unaware of how much the shell can accomplish. Using the shell, you can generate databases and web pages from sets of files, automate monotonous admin tasks such as system backups, monitor your system's health and activity, identify network bottlenecks and system resource hogs, and more. This book will show you how to do all this and much more. This book, now in its third edition, describes the exciting new features in the newest Linux distributions to help you accomplish more than you imagine. It shows how to use simple commands to automate complex tasks, automate web interactions, download videos, set up containers and cloud servers, and even get free SSL certificates. Starting with the basics of the shell, you will learn simple commands and how to apply them to real-world issues. From there, you'll learn text processing, web interactions, network and system monitoring, and system tuning. Software engineers will learn how to examine system applications, how to use modern software management tools such as git and fossil for their own work, and how to submit patches to open-source projects. Finally, you'll learn how to set up Linux Containers and Virtual machines and even run your own Cloud server with a free SSL Certificate from letsencrypt.org.

Who is this book for?

If you are a beginner or an intermediate Linux user who wants to master the skill of quickly writing scripts and automate tasks without reading the entire man pages, then this book is for you. You can start writing scripts and one-liners by simply looking at the relevant recipe and its descriptions without any working knowledge of shell scripting or Linux. Intermediate / advanced users, system administrators / developers, and programmers can use this book as a reference when they face problems while coding.

What you will learn

  • • Interact with websites via scripts
  • • Write shell scripts to mine and process data from the Web
  • • Automate system backups and other repetitive tasks with crontab
  • • Create, compress, and encrypt archives of your critical data.
  • • Configure and monitor Ethernet and wireless networks
  • • Monitor and log network and system activity
  • • Tune your system for optimal performance
  • • Improve your system s security
  • • Identify resource hogs and network bottlenecks
  • • Extract audio from video files
  • • Create web photo albums
  • • Use git or fossil to manage revision control and interact with FOSS projects
  • • Create and maintain Linux containers and Virtual Machines
  • • Run a private Cloud server

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2017
Length: 552 pages
Edition : 3rd
Language : English
ISBN-13 : 9781785882388
Tools :

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 29, 2017
Length: 552 pages
Edition : 3rd
Language : English
ISBN-13 : 9781785882388
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 803.97
Working with Linux ??? Quick Hacks for the Command Line
zł177.99
Linux Shell Scripting Cookbook
zł221.99
Linux: Powerful Server Administration
zł403.99
Total 803.97 Stars icon

Table of Contents

13 Chapters
Shell Something Out Chevron down icon Chevron up icon
Have a Good Command Chevron down icon Chevron up icon
File In, File Out Chevron down icon Chevron up icon
Texting and Driving Chevron down icon Chevron up icon
Tangled Web? Not At All! Chevron down icon Chevron up icon
Repository Management Chevron down icon Chevron up icon
The Backup Plan Chevron down icon Chevron up icon
The Old-Boy Network Chevron down icon Chevron up icon
Put On the Monitors Cap Chevron down icon Chevron up icon
Administration Calls Chevron down icon Chevron up icon
Tracing the Clues Chevron down icon Chevron up icon
Tuning a Linux System Chevron down icon Chevron up icon
Containers, Virtual Machines, and the Cloud Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(4 Ratings)
5 star 50%
4 star 0%
3 star 50%
2 star 0%
1 star 0%
RAGHAV Mar 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
book recieved in great condition.
Amazon Verified review Amazon
Raj Jun 03, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
👍👍👍👍👍👍✌✌✌✌✌🕵️‍♀️🕵️‍♀️💗
Amazon Verified review Amazon
qishan2002 Jan 08, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Very lengthy illustration of the command options some of which are quite useful and some are quite obscure and we can do without. The book is overall weak in with respect to scripting -- have commands work together.
Amazon Verified review Amazon
Amazon Customer Jan 28, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I would expect a book about Linux Shell Scripting to be be about actually scripting. This book shows you how to write glorified commands but is anemic with regards to actual scripting. If your goal is to write better commands and even how to structure them, this is your book but with hardcore scripting techniques, I can't reasonably encourage you to purchase this one.
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.