Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
Bash Quick Start Guide
Bash Quick Start Guide

Bash Quick Start Guide: Get up and running with shell scripting with Bash

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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

Bash Quick Start Guide

Bash Command Structure

In this chapter, we'll learn the structure of a simple Bash command line, and the basics of quoting. You should read this chapter all the way through, paying careful attention especially to the material on quoting, even if you feel you already know how Bash commands work.

In this chapter, you will learn the following:

  • How to use Bash interactively
  • The structure of simple commands
  • How to quote data safely
  • How to run several commands with one command line
  • How to make a command line stop if a command fails
  • How to run a command in the background

Using Bash interactively

If Bash is your login shell, and you log in to the system from a terminal or terminal emulator, then it will start in interactive mode. In this mode, Bash will present a prompt when it's ready to accept a command from your terminal. This differs from non-interactive or batch mode, where commands are read from some other source, such as a script file. We will use interactive mode in this chapter to experiment with the basics of shell script command line grammar.

Nearly all of the features available to Bash in scripts are also available on the interactive command line, and they behave essentially the same way as if you ran them from a script. This allows you to treat the interactive command line as a live scripting environment: you can assign variables, create functions, and manage control flow and processes.

...

Interactive key bindings

In this book, we won't focus too much on the interactive keyboard shortcuts in Bash. This is because it's more useful to know the syntax of the shell scripting language than it is to know key bindings.

To read more about Bash key bindings, after you have finished this book, consult the Bash manual under the READLINE section, and the GNU Readline manual:

$ man bash
$ man 3 readline

Simple commands

At an interactive Bash prompt, you can enter a command line for Bash to execute. Most often while in interactive mode, you would issue only one simple command at a time, ending each command with Enter. You would then wait for each command to finish before entering the next one, examining any output or errors that it passes to your terminal after each command.

A simple command consists of at least a command name, possibly with one or more arguments, each separated by at least one space. The full definition can also include environment variable assignments and redirection operators, which we'll explore in later chapters.

Let's consider the following command:

$ mkdir -p New/bash

This simple command consists of three shell words:

  • mkdir: The command name, referring to the mkdir program that creates a directory
  • -p: An option string for mkdir that specifies...

Shell metacharacters

So far, all of our examples of commands and arguments have been single unquoted shell words. However, there is a set of metacharacters that have a different meaning to Bash, and trying to use them as part of a word causes problems.

For example, suppose you want to create (touch) a new file named important file. Note that there's a space in the name. If you try to create it as follows, you get unexpected results:

$ touch important file

If we list the files in the directory after running this, using ls -1 to put all the names on separate lines, we can see we've actually created two files; one named important, and one named file:

$ ls -1
file
important

This happened because the space between the two words separated them into two separate arguments. Space, tab, and newline are all metacharacters. So are | (pipe), & (ampersand), ; (semicolon), ( and...

Quoting

The way you can reliably include characters that are special to Bash literally in a command line is to quote them. Quoting special characters makes Bash ignore any special meaning they may otherwise have to the shell, and instead use them as plain characters, like a-z or 0-9. This works for almost any special character.

We say "almost", because there's one exception: there's no way to escape the null character (ASCII NUL, 0x00) in a shell word.

Quoting is the most important thing that even experienced people who write shell script sometimes get wrong. Even a lot of very popular documentation online fails to quote correctly in example scripts! If you learn to quote correctly, you will save yourself a lot of trouble down the line. The way quoting in shell script works very often surprises people coming from other programming languages.

We will look at...

Running commands in sequence

You can send an interactive command line with more than one simple command in it, separating them with a semicolon, one of several possible control operators. Bash will then execute the commands in sequence, waiting for each simple command to finish before it starts the next one. For example, we could write the following command line and issue it in an interactive Bash session:

$ cd ; ls -a ; mkdir New
Running cd on its own like this, with no directory target argument, is a shortcut to take you to your home directory. It's the same as typing cd ~ or cd -- "$HOME".

For this command line, note that even if one of the commands fails, Bash will still keep running the next command. To demonstrate this, we can write a command line to include a command that we expect to fail, such as the rmdir call here:

$ cd ; rmdir ~/nonexistent ; echo &apos...

Exit values

We can tell it was the rmdir command in the previous section that failed, because rmdir is the first word of the error message output. We can test the command in isolation, and look at the value of the special $? parameter with echo, to see its exit status:

$ rmdir ~/nonexistent
rmdir: failed to remove '/home/bashuser/nonexistent': No such file or directory
$ echo $?
1

The rmdir program returned an exit value of 1, because it could not delete a directory that didn't exist. If we create a directory first, and then remove it, both commands succeed, and the value of $? for both steps is 0:

$ mkdir ~/existent
$ echo $?
0
$ rmdir ~/existent
$ echo $?
0

Examining the exit values for the true and false built-in Bash commands is instructive; true always succeeds, and false always fails:

$ true ; echo $?
0
$ false ; echo $?
1

Bash will also raise an exit status...

Stopping a command list on error

Most of the time when programming in Bash, you will not actually want to test $? directly, but instead test it implicitly as success or failure, with language features in Bash itself.

If you wanted to issue a set of commands on one command line, but only to continue if every command worked, you would use the double-ampersand (&&) control operator, instead of the semicolon (;):

$ cd && rmdir ~/nonexistent && ls

When we run this command line, we see that the final ls never runs, because the rmdir command before it failed:

rmdir: failed to remove '/home/user/nonexistent': No such file or directory

Similarly, if we changed the cd command at the start of the command line to change into a directory that didn't exist, the command line would stop even earlier:

bash$ cd ~/nonexistent && rmdir ~/nonexistent...

Running a command in the background

There are some situations in which you might want to continue running other commands as you wait for another one to complete, to run more than one job in parallel. You can arrange for a command to run in the background by ending it with a single ampersand (&) control operator.

You can try this out by issuing a sleep command in the background. The sleep built-in Bash command accepts a number of seconds to wait as an argument. If you enter such a command without the &, Bash won't accept further commands until the command exits:

$ sleep 10
# Ten seconds pass... $

However, if you add the & terminator to start the job in the background, the behavior is different: you get a job control number and a process ID, and you are returned immediately to your prompt:

$ sleep 10 &
[1] 435
$

You can continue running other commands as normal...

Summary

Even if you feel that you already know the basic structure of a Bash command well, carefully looking at the structure of a typical command line and knowing the rules of string quoting can make it much clearer what's wrong when something doesn't behave as expected. We use single quotes to keep characters literal, and double quotes to safely perform expansion for variables and substitutions. Developing disciplined habits with quoting and understanding how Bash runs commands in sequence is helpful not just for scripting, but for interactive command line work as well.

Having learned the structure of a Bash command line, in the next chapter we'll apply it to learning some essential commands that will form the basis of many shell scripts.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Demystify the Bash command line
  • Write shell scripts safely and effectively
  • Speed up and automate your daily work

Description

Bash and shell script programming is central to using Linux, but it has many peculiar properties that are hard to understand and unfamiliar to many programmers, with a lot of misleading and even risky information online. Bash Quick Start Guide tackles these problems head on, and shows you the best practices of shell script programming. This book teaches effective shell script programming with Bash, and is ideal for people who may have used its command line but never really learned it in depth. This book will show you how even simple programming constructs in the shell can speed up and automate any kind of daily command-line work. For people who need to use the command line regularly in their daily work, this book provides practical advice for using the command-line shell beyond merely typing or copy-pasting commands into the shell. Readers will learn techniques suitable for automating processes and controlling processes, on both servers and workstations, whether for single command lines or long and complex scripts. The book even includes information on configuring your own shell environment to suit your workflow, and provides a running start for interpreting Bash scripts written by others.

Who is this book for?

People who use the command line on Unix and Linux servers already, but don't write primarily in Bash. This book is ideal for people who've been using a scripting language such as Python, JavaScript or PHP, and would like to understand and use Bash more effectively.

What you will learn

  • Understand where the Bash shell fits in the system administration and programming worlds
  • Use the interactive Bash command line effectively
  • Get to grips with the structure of a Bash command line
  • Master pattern-matching and transforming text with Bash
  • Filter and redirect program input and output
  • Write shell scripts safely and effectively

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 28, 2018
Length: 186 pages
Edition : 1st
Language : English
ISBN-13 : 9781789534085
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 : Sep 28, 2018
Length: 186 pages
Edition : 1st
Language : English
ISBN-13 : 9781789534085
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 82.97
Fundamentals of Linux
€24.99
Bash Cookbook
€32.99
Bash Quick Start Guide
€24.99
Total 82.97 Stars icon
Banner background image

Table of Contents

9 Chapters
What is Bash? Chevron down icon Chevron up icon
Bash Command Structure Chevron down icon Chevron up icon
Essential Commands Chevron down icon Chevron up icon
Input, Output, and Redirection Chevron down icon Chevron up icon
Variables and Patterns Chevron down icon Chevron up icon
Loops and Conditionals Chevron down icon Chevron up icon
Scripts, Functions, and Aliases Chevron down icon Chevron up icon
Best Practices Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Kinger Mar 12, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This was the only book I could find that lays out best practises for bash scripting, such as proper quoting, variable naming, and parameter expansion. There are many books that will show you a lot of interesting script examples but they'll also teach you bad habits that might get you into trouble down the road. This would be a great first book for anyone looking to write safe, portable scripts. Highly recommended!
Amazon Verified review Amazon
WF May 01, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I purchased a few Bash starter books to review for a future class I'll be teaching. I actually ordered this one by accident thinking this was a beginners book. First, let me say it's an excellet book. And I'll definitely be using this book for teaching Bash script writing for web servers. Which is what this is for...Bash script writing :). If your looking to learn Bash this might not be the first book you would want to go with. But it definitely would be the second. I recomed Bash In Easy Steps. From the Easy Steps series. It will get you up and going on Bash and all the commands quick and easy. A middle schooler could understand it. I'm teaching my niece in 1st grade from that book. The next step would definitely be this book. It will get you to the next steps. Where you can write backup scripts for Wordpress, and MySQL to basic and advance automation scripts for your home PC or server.
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.