Skip to content
ImagineWorld

Automating Tasks with Shell Scripts

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-10-automating-tasks-with-shell-scripts
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleAutomating Tasks with Shell Scripts
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Automating Tasks with Shell Scripts

Section titled “Chapter 10 — Automating Tasks with Shell Scripts”

Sometimes, you’ll find yourself repeating the same few commands over and over, perhaps with slight variations. You reach the point of frustration, and say, “That’s it; I’m scripting this.” Being a CLI wizard, you do the following:

  1. Run tail -n 20 ~/.bash_history > myscript.sh to create a file that contains the last 20 Bash commands you ran.
  2. Then run bash myscript.sh to execute it.

Although this isn’t the recommended procedure (we’ll get to that in this chapter), it’s a perfectly valid way to create and run a Bash script.

This chapter is a Bash scripting crash course. Like any programming crash course, it is completely useless unless you actually follow along, type in all the code yourself, and run it in your own Linux environment. In addition to showing you the subset of Bash’s syntax which is considered modern and best-practice, we’ll give you plenty of tips from our hard-earned experience over the years, calling out common pitfalls and sharp edges.

Bash isn’t our favorite language, but sometimes it’s exactly the right tool for the problem you face. We’ll try to give you an understanding of this as well.

In this chapter, we will cover the following:

  • Bash scripting basics
  • Bash versus other shells
  • Shebangs and executable text files
  • Testing
  • Conditionals

Shell scripts are an indispensable tool for any developer; even if you’re not writing scripts on a weekly basis, you’ll be reading them. In this chapter, we’ll cover the basics you need to know so that you feel comfortable when, for example:

  • You’re confronted by a shell script that someone wrote a few years ago, for example “Can you check to see if we can reuse the automation scripts that Steve wrote before he left for Google?”
  • You see an opportunity to write your own shell script, when you have a job that existing shell programs already solve (filtering, searching, sorting output, and feeding one program’s output into another one).
  • You want to control precisely what goes into each Docker layer as you build up an image.
  • You need to coordinate other software in the context of a Linux server’s operating system: startup ordering, error checking, aborting early between programs, and so on.

There are innumerable use cases where a shell script is just the right size and shape for your problem space. After this chapter, you’ll have the skills you need to write that custom script.

Bash can be learned like any other programming language. It’s got an environment (Unix or Linux), a kind of standard library (any CLI-driven program installed on the system), variables, control flow (loops, testing, and iteration), interpolation, a few built-in data structures (arrays, strings, and booleans – sort of), and more.

This entire book assumes that you’re a software developer and, therefore, know how to program, so rather than teach you about these standard programming-language features, we’ll simply show you what they look like in Bash, along with some advice on idiomatic use (or common misuse).

Like any programming language, Bash has variables that can either be empty or set to a value. Unset variables are simply “empty,” and Bash will happily use them without panicking unless you set the -u (error on unset variables) option via set -u.

To set a variable, use the equals sign.

FOOBAR=nice will set the FOOBAR variable to the value nice.

There are no types in Bash – it’s about as untyped as a programming language can get.

A variable symbol itself can contain letters, numbers, and underscores, but may not start with a number.

It is common practice to use uppercase variable names for environment variables and lowercase ones inside of Bash scripts. These variable names typically use underscores to separate individual words. When using numbers inside of variable names, avoid starting with digits. Bash forbids this. As with other languages, it’s a good practice for names to indicate what a variable is used for and whether it is a constant, or use a plural name for an array:

  • Illegal: %foo&bar=bad
  • Illegal: 2foo_bar=bad
  • Legal but bad: foo_BAR123=still_very_bad
  • Good environment variable: PORT=443
  • Good: local_var=512
  • Good environment variable: FOO_BAR123=good
  • Good local array var: words=(foo bar baz)

To use a variable, reference it with the $ character:

$ echo $FOOBAR
nice

A huge variety of shell programs exist for Unix-like environments; you could argue that one of the major reasons for Unix’s popularity is the fact that it’s always been an environment with essentially no barriers to scripting and automation.

This chapter teaches you how to write your own scripts in Bash. Much of what you’ll learn here will also work on other shells (for example, ksh and other common minimal shells that you’ll find at /bin/sh), but we’re focused on Bash here.

If you’re writing a shell script, Bash strikes the perfect balance between wide availability and a language feature set that’s large enough to make it comfortable to write small programs.

Shebangs and executable text files, aka scripts

Section titled “Shebangs and executable text files, aka scripts”

In Unix-like systems, a “script” is just an executable plaintext file. The operating system (often called “the kernel” in Linux) looks at the very first line to determine which interpreter to feed the file’s content into.

That first line is the so-called “shebang” (or hashbang), and it consists of a hash and an exclamation mark (#!) character, followed by the path to the interpreter that is used to execute the file’s code. Here’s an example shebang line:

#!/usr/bin/env bash

When the kernels of Unix-like systems run a file with the executable bit set, they’ll take a look at the first bytes. This might contain a magic number. This number can be part of binary files or some human-readable character, like in the shebang. The kernel uses this information to know whether there is a proper way to execute it. This, for example, prevents situations where the kernel would try to execute an image file and crash. Depending on the system, the kernel or the shell will make sure that the command following is executed. The env program will run the command and take the PATH environment variable into account to find and execute bash.

While a hash denotes a comment in most scripting languages and would, therefore, be ignored by the interpreter, this special comment at the beginning of a file tells the operating system which command to run to interpret the rest of the file. Here are some common examples you’ll see:

  • #!/bin/sh: use this specific shell program at this specific filesystem location
  • #!/usr/bin/python3: use this specific Python binary
  • #!/usr/bin/env python: use the env program to figure out which Python binary to use in this environment (different systems may have different versions of the same program installed, at different paths)

While you will see all of these variants, the best option is to always use /usr/bin/env for portability. /bin/sh is the exception here, since every POSIX-compatible system is required to have a POSIX-compatible shell in this location.

Since the shebang line is executed as a command, arguments may also be passed. And while it can be a good idea to keep things simple, a common theme is to pass extra arguments to shells, especially to Bash, which is often used for large scripts because it has extra features compared to the smaller shells usually found at /bin/sh.

In Bash scripts, you will often see the -e, -u, -x, -o pipefail arguments passed. You may find these arguments in the shebang line itself:

#!/usr/bin/env bash -euxo pipefail

Or, as the next statement, using the set command in Bash, which sets arguments or options:

#!/usr/bin/env bash
set -eu -o pipefail

Setting these options makes Bash behave a bit more like the programming languages you’re used to, by:

  • Exiting immediately if any component of a command pipeline fails, and
  • Treating unset variables as fatal errors.

Here’s a breakdown of the documentation for these options, along with a useful debug option (-x) as a bonus:

  • -o pipefail: When using pipes, this will make sure that errors happening in the pipeline will be passed on. If more than one error happens, the rightmost will be used.
  • -e: If there is an error or a command fails, this will make sure that the shell script exits immediately.
  • -u: throw an error if any unset variables are used.

For debugging, -x is useful:

  • -x: This will enable tracing. This means that each command will be written to standard error before executing it.

All arguments, except –o pipefail, can be found in most Unix shells. For more information on the options that Bash contains, see its manual page: https://manpages.org/bash.

Here’s something to keep in mind: /bin/sh is a standardized path in POSIX leading to any POSIX-compatible shell. You can count on it to be there on ANY Linux or Unix system. Typically, this is not bash, but a more minimal shell, offering just enough functionality to satisfy the POSIX standard, which allows you to write very portable shell scripts. For all other shells and interpreters your script might need, it’s best practice to use the #!/usr/bin/env prefix for any other case. This makes sure that the correct path from PATH is used, and it will prevent a “command not found” error when the binary isn’t located in /usr/bin/.

There are various scenarios in which /usr/bin/bash or /bin/bash wouldn’t be the right path. For example:

  • A package manager or company-specific configuration scripts will often install the interpreter in a different place than it would be on your development system.
  • Someone installing software manually, for example, to work around or reproduce a bug, often places the resulting binary in /usr/local.
  • Virtual environments of various scripting languages will put binaries into a subdirectory of each source code project/repository.
  • People installing the interpreter without root permissions, for example, in their home directory.
  • People using a version manager for the interpreter (rvm, nvm, and so on).
  • Various Unix-like operating systems and some Linux distributions don’t install third-party packages into /usr/.

While many people can’t imagine their script ever ending up in such a non-standard place, chances are good that you’ll run into this eventually. Instead of risking your software breaking in these cases, it’s a good idea to simply get into the habit of writing /usr/bin/env bash (or whatever interpreter your code is written for) in your scripts. This prevents someone else – or your very tired future self, woken up by a pager at 3 in the morning – from having to notice, troubleshoot, find, or make such changes on source files when they break due to a minor change in the environment.

One special character you should use often is the hash symbol (#), which makes everything on the line following the symbol a comment that the interpreter ignores.

Other characters have special meaning in Bash, and they need to be escaped with a forward slash (\) when you use them as part of a variable’s value. Here are some of them:

  • Quotes (" and ')
  • Brackets and parentheses ({, }, [, ], and (, ))
  • Carets (< and >)
  • Tilde: ~
  • Asterisk (the “glob character” in Bash): *
  • Ampersand: &
  • Question mark: ?
  • Common operators: !, =, |, and so on

Escape them like you do in most other programming languages:

$ FOO="jaa\$\'"

One of the benefits and major use cases of shell scripting is that any command is easily accessible. A very common example of this is command substitution. This is useful when you want to use the output of one or more commands. You can do this with command substitution:

echo "Right now, it's $(date)"

This executes those commands – in this case, just date, but it could also be a complex expression that you’ve piped together. Another way to do the same is to use backticks. The following example will have the same output:

echo "Right now, it's \`date\`"

The testing commands shown here are usually used along with if/else control flow statements. Both the string testing function ([[) and the arithmetic testing function ((() return 0 if the test evaluates to a true value, or 1 if the test evaluates to false. This is due to the 0 exit code of commands indicating success, and it is different from other programming languages you might know that typically evaluate a zero value as false. There is no native boolean data type in Bash; the integers 0 and 1 are used in boolean contexts like this one. Sometimes, the variables true and false are initialized and used throughout a script.

Here are some basic boolean operators that you can use to construct statements in Bash – essentially, what you’re used to from other languages:

  • ! – not (negation)
  • && – and
  • || – or

These operators can be used with both string and arithmetic test types:

  • == – is equal to
  • != is not equal to

The [[ compound command allows you to perform (and combine) “string” comparisons. As mentioned before, Bash doesn’t have the kind of strict data types that you’re used to from other programming languages, so we’re calling them “string” or “string-like” comparisons because that’s a familiar concept to software developers.

If the user’s home directory does not exist, create it:

if [[ ! -d $HOME ]]; then
echo "Creating home directory: ${HOME}..."
mkdir -p $HOME
echo "done"
fi

That ! character is a Bash negation, so you can read the first line of this example as if NOT (test) is-a-directory $HOME, then….

Here’s a slightly more complicated example. If the user’s home directory does not exist, OR if the ALWAYSCREATE variable is set to yes, create the home directory:

ALWAYSCREATE=yes
if ! [[ -d $HOME ]] || [[ $ALWAYSCREATE == yes ]]; then
echo "Creating home directory: ${HOME}..."
mkdir -p $HOME
echo "done"
fi
  • -z is unset (used for variables)
  • -n is non-zero (set – used for variables)
  • =~ is a left operand that matches a regular expression (right operand), for example [[ foobar =~ f*bar ]]
  • -d: a directory
  • -e: exists
  • -f: a regular file
  • -S: a socket file
  • -w: writable, from the perspective of this Bash process

Arithmetic evaluated in a (( test will set the test’s exit value to 1 if the expression evaluates to 0; otherwise, it will return an exit status of 0. This makes testing quite intuitive, using operators you already know from virtually every other programming language:

  • > and >= – greater-than and greater-than or equal-to
  • < and <= – less-than and less-than or equal-to
  • == – test equality

(( $SOME_NUMBER == 24 )) is a fairly straightforward arithmetic test. Let’s see how it behaves.

For the number 24:

→ SOME_NUMBER=24
→ (( $SOME_NUMBER == 24 ))
→ echo $?
0

The “ echo $?” command prints out the exit status of the previous command, which lets us see what the arithmetic test actually evaluated to. For other values, including non-numeric ones:

→ SOME_NUMBER=foobar
→ (( $SOME_NUMBER == 24 ))
→ echo $?
1

If $SOME_NUMBER is unset (for example, [[ -z $SOME_NUMBER ]] ):

→ unset SOME_NUMBER
→ (( $SOME_NUMBER == 24 ))
zsh: bad math expression: operand expected at \`== 24 '

So, to review:

  • (( $SOME_NUMBER == 24 )) will evaluate to 0 if the SOME_NUMBER variable is set to 24.
  • If $SOME_NUMBER is set to a value OTHER THAN 24 (including a non-numeric value), it will evaluate to 1.
  • If $SOME_NUMBER is unset, you’ll get an error because your arithmetic test doesn’t have a left operand to use for the comparison.

A Bash if statement is usually found in this form:

if [[ $TEST ]]; then $STATEMENTS else $OTHER_STATEMENTS fi

Remember a few things about this form before we look at examples:

  • if and fi begin and terminate the if block, respectively.
  • ; delimits statements in Bash; add one right after the test.
  • [[ and ]] delimit your test expression.
  • The else clause is optional.

Here’s what the if statement looks like in Bash:

if [[ -e "example.txt" ]]; then
echo "The file exists!"

If you want to tack an else clause onto this structure, you can!

if [[ -e "example.txt" ]]; then
echo "The file exists!"
else
echo "The file does not exist!"
fi

Bash loops come in the general format for / do / done. They also support break and continue statements, which break out of the loop and skip to the next iteration, respectively.

Bash supports C-style loops, with an initializer expression, a conditional expression, and a counting expression:

for (( i=0; i<=9; i++ ))
do
echo "Loop var i is currently $i"
done

Let’s talk about iteration with for...in loops. Try running the following in your shell:

for i in 1 2 3 4 5
do
echo $i
done

Here’s a loop with some control flow inside:

for os in FreeBSD Linux NetBSD "macOS" DragonflyBSD
do
echo "Checking out ${os}..."
if [[ "$os" == 'NetBSD' ]]; then
echo "(I'm pretty sure this would run on my toaster, actually)"
fi
sleep 1
done

Another common control structure you might be familiar with from other programming languages is the while loop. In Bash, this works very similarly. To break out of a loop, the break statement can be used.

The following script will read the lines.txt file line by line until it encounters the STOP line. The last line also shows how you can pipe a file into a loop. The read command will take care of processing the file line by line:

file="lines.txt"
while read line; do
if [[ $line == "STOP" ]]; then
echo "Encountered STOP. Exiting loop."
break
fi
echo "Processing: $line"
# Additional commands to process $line can be added here.
done < "$file"

Exporting a variable by prefixing it with export ensures that any subshells spawned from your script’s process will also have access to that variable’s value. It’s a way of ensuring that a variable is propagated down to any future sub-scopes (or sub-namespaces) of your current shell’s variable scope or namespace.

Set a variable in your shell:

MYDIR=$HOME

Create and run this script (warning: this will fail!):

#!/usr/bin/env bash
LISTING=$(ls "${MYDIR}/Documents")
echo $LISTING

You’ll see an error, ls: /Documents: No such file or directory, because running this script spawned a subshell that did not have access to unexported variables in its parent shell (the shell that spawned it, in other words your interactive shell). Letting subshells access your variables must be done explicitly, via the export keyword:

export MYDIR=$HOME

Rerun the example script now that you’ve exported the variable, and you’ll see that it can now access the MYDIR variable.

We generally recommend that by the time you find yourself needing Bash functions, you will have found another language to write your growing program in. However, sometimes Bash is still the right language for a problem, and we want to show you the absolute basics, with a strong bias toward how we recommend using them.

Define a function by using the function keyword:

function my_great_function {
$EXPRESSIONS
}

Call functions by simply invoking their name:

my_great_function

Bash works with a more-or-less global scope – more accurately, per (sub)shell. Many modern programming languages give you a separate function scope to work with, so function state doesn’t pollute global state after a function exits.

Using local variables in your functions will protect you from this, and we recommend you use them:

#!/usr/bin/env bash
important_var=somevalue
function local_var_example() {
local important_var="changed this locally, don't worry"
echo "local_var_example: ${important_var}"
}
function bad_example() {
important_var="this is mutating the global var because I'm bad, and I should feel bad."
echo "bad_example: ${important_var}"
}
echo "before functions: ${important_var}"
local_var_example
echo
echo "after local_var_example: ${important_var}"
echo
bad_example
echo "after bad_example: ${important_var}"
exit 0

Run this code yourself and see the difference that using local vars makes.

When you run scripts, you’ll often want to redirect their output:

  • To another program (via a pipe – | – see Chapter 11, Pipes and Redirection, for more details)
  • To a regular file (like a log file)
  • To a special location like /dev/null, which can act as a kind of black hole for data you don’t need

Aside from pipes, here are the most common input/output redirection tricks you’ll see in the wild.

This is often used to grab input from a file, instead of from the shell spawning a process:

grep foobar < stuff.txt

The > symbol will stream output to wherever you point it, overwriting anything that’s already there if it’s a regular file:

ps aux | grep foo > /var/log/foo_overwrite.log

Every time you run this, the output of ps aux | grep foo will be written to /var/log/foo_overwrite.log, overwriting any existing file content.

Using >> instead will append to the output file, leaving any existing content intact. This is usually what you want for log files:

echo $(date && cat /proc/stat) >> /var/log/kernelstate.log

Sometimes, you want to redirect both standard output and standard error to a file:

consul agent -dev >> /var/log/consul.log 2>&1 &

This command runs Hashicorp’s Consul in dev-mode and backgrounds the process (the & symbol at the end), redirecting standard output to a log file. 2>&1 tells Bash to “redirect file descriptor 2 (STDERR) to the same place as 1 (STDOUT)” – in this case, that’s /var/log/consul.log.

You already know about file descriptors – STDIN, STDOUT, and STDERR. What if you only want to redirect a standard error to a different file than a standard output?

To accomplish what’s known as “string interpolation” in most programming languages – substituting part of a string with the value of a variable – you want Bash’s variable interpolation, ${}.

Try it yourself:

MYNAME=dave
echo "I can't do that, ${MYNAME}."

There are other ways to interpolate variables in Bash, but this is our favorite way, since it has the lowest chance of breaking your program due to unexpectedly-shaped input (spaces, special characters, and so on).

If you are going to use a variable as a string-like value, use this syntax – even if that variable is by itself and doesn’t really need to be interpolated into another string:

NAME="${MYNAME}"

This will prevent many strange bugs and behaviors with Bash, so it’s a good habit to get into.

Note

When working with variable interpolation, you’ll almost always want to run Bash with the -u option (either by calling it with -u, or by using set -euo pipefail at the beginning of your scripts, as we recommend). This will prevent you from having to check for zero values before you use a variable.

Bash has innumerable features, many of which we’re not covering here. If you need to dig deeper into the Bash language and environment, there are many books and tons of free resources on the web. The Bash manpage (man bash) is a good start too, now that you’re oriented.

We expect you to encounter many Bash scripts over the course of your career. However, it’s very likely that you’ll spend more time reading and deciphering existing scripts than writing large new Bash programs. Bash is an amazing fit for small problems and system tasks that lend themselves to being solved with existing software, which just needs to be tied together into a solution. It’s often a terrible fit for large problems that extend beyond tying together standard Linux and Unix programs.

With Bash, we find that:

  • Small is better than large
  • Clear is better than clever
  • Safe is better than sorry

It’s not uncommon to replace Bash scripts with tools written in a different programming language (often Python) as they grow. That’s not a dig against Bash! It’s perfect at filling the niche that it occupies, which is why it’s been so widespread for so long. If you occasionally stop to ask yourself, “Is a Bash script still the right solution for this problem?” you’ll be just fine.

This chapter was a no-punches-pulled, drink-from-the-fire-hydrant Bash scripting crash course. It’s dense, but it covers all the basics you need to become an effective Bash scripter. Work through it more than once if you have to. In addition to the syntax, we covered what we think are best practices that make writing readable, maintainable real-world scripts easier (or at least possible).

Practice, practice, practice – preferably on real-world problems you have, not just toy examples. There’s no faster way to get good.