Automating with Shell Scripts
local graph
Chapter 4 — Automating with Shell Scripts
Section titled “Chapter 4 — Automating with Shell Scripts”In this chapter, we’re going to demonstrate system administration task automation with shell scripts. We are going to illustrate several ways of handling scripting using Bash shell. The plan is to create a script that will automate the creation of the database dump. This task, while easy, will demonstrate how things can go sideways and how to handle those situations.
In this chapter, we will cover the following topics:
- Backing up a database
- Understanding scripting
- Understanding Bash built-ins and grammar
- Understanding the backup script – first steps
- Handling errors and debugging
Technical requirements
Section titled “Technical requirements”For this chapter, you will require a Linux system where you can install packages and are not afraid to break things in the process. To that end, a virtual machine would be most preferred, typically running on an old computer that you can reinstall from scratch. We do not expect to break anything, but during learning, this may happen.
Backing up a database
Section titled “Backing up a database”In terms of most common databases, such as MySQL and PostgreSQL, there are at least two different ways to back up a database:
- Take a database dump by extracting all current data, along with the database schema
- Copy replication logs
In cloud environments, you can also take a snapshot of the disk database where the backup is being saved.
A database dump can also be used as a full backup. Replication logs aren’t self-sufficient database dumps, so you will need to combine them with a full backup. This is called an incremental backup.
Doing a full backup can take a long time, especially for big databases. While it’s running, the database puts a lock on its data files, so it doesn’t save new data on the disk; instead, it stores everything in the replication logs until the database lock is released. For large databases, this operation can take hours. Because of that, we will be creating a full backup once a week and copying all replication logs every hour. Additionally, we will be creating a daily disk snapshot of our AWS database instance.
With this knowledge, we can start creating the most basic version of our script.
Understanding scripting
Section titled “Understanding scripting”A shell script is a simple text file filled with commands. Unlike compiled programs, shell scripts are not evaluated before execution, but rather while they are being executed. This makes for a very quick development process – there’s no compilation at all. But at the same time, the execution is a bit slower. Also, the errors that the compiler would have caught surface during execution and can often lead to script exiting.
On the upside, there’s not much to learn when you are writing a script – much less than when you are writing a program in C or Python. Interacting with system commands is as simple as just typing their names.
Bash lacks a lot of sophistication in programming languages: there are not many data types and structures, there’s very rudimentary control of scope, and the memory implementation is not meant to be efficient with scale.
There’s not one good rule of thumb for choosing when to write a script and when to develop a program. However, there are some points to consider. A good candidate for a shell script is as follows:
- It’s not very long. We can’t give you a rule, but when you start to go into hundreds of lines, it may be good to consider using Python or splitting it into several scripts.
- It interacts with system commands, sometimes a lot. You can consider it an automated way of running those commands.
- It doesn’t do a lot of data handling. There are few arrays, strings, and numbers. That’s all.
- It doesn’t do any system calls. Shell scripts are not there for system calls. There’s no straightforward way to do it.
The basic structure of a shell script is as follows:
#!/bin/bashecho "Hello world"The first line starts with the so-called she-bang. It’s being used to tell the system which interpreter (in this case, it’s Bash) to use to run this script. In a lot of scripts found online, she-bang looks like this:
#!/usr/bin/env bashUsing the env command has a big advantage and disadvantage at the same time. The advantage of using it is that it will use a Bash executable that is first in the current user PATH environment variable. It all depends on the purpose. The env command also won’t let you pass any arguments to the interpreter you choose.
The second line of the preceding script simply displays Hello world. It uses a built-in command echo that does just that – it displays whatever text you put as input.
Now, to execute this script, we will need to save it to a file. It’s good practice to end this file with a .sh or .bash suffix. There are two ways to execute this new script – by invoking the interpreter with a script name or by directly executing the script by its name:
admin@myhome:~$ bash ./myscript.shHello worldadmin@myhome:~$To directly execute the script, we will need to change its permissions so that it can be executed; otherwise, the system won’t recognize it as something it can execute:
admin@myhome:~$ chmod +x myscript.shadmin@myhome:~$ ./myscript.shHello worldadmin@myhome:~$Similarly, we could easily set Python or any other shell as an interpreter of our script.
For now, let’s focus on Bash and look at some built-in Bash commands that we’re going to use.
Understanding Bash built-ins and grammar
Section titled “Understanding Bash built-ins and grammar”Let’s get back to the fundamentals before we start creating a script. First, we will look into the Bash scripting language syntax and its limitations.
Built-in commands are commands that are integral to Bash and are the main scripting syntax we are going to use. Bash will try to execute any other commands from the system it runs on.
Just like any other interpreted language (for example, Python or Ruby), Bash has unique syntax and grammar. Let’s look into it.
Bash, similar to other programming languages, interprets files from top to bottom and from left to right. Each line usually contains one or more commands. You can glue several commands together in one line using a pipe (|) or double pipe character (||), semicolon (;), or double ampersands (&&). It’s useful to remember that double pipes have the same function as logical OR and double ampersands have the same function as logical AND. This way, you can run commands in sequence and execute the next command depending on the outcome of the previous command, without using more complex conditional statements. This is called a list or chain of commands:
commandA && commandBIn the preceding command, you can see an example of using double ampersands. Here, commandB will only be executed if commandA is successfully executed. We can chain more commands like this by adding || at the end of the chain.
commandA || commandBThis example, on the other hand, shows how to use a double pipe. Here, commandB will only be executed if commandA fails to execute.
Bash (or any other shell in Linux) determines whether a command failed to execute or exited with success by using return codes. Every command needs to exit with a positive number – zero (0) is a code for success, and any other code is a failure. If you chain multiple commands with AND(&&) or OR (||), the return status of the whole line will be determined by the previous command that was executed.
What about a single ampersand (&) after a command? It has an entirely different function – it will execute a command it is after in the background and the script will continue running without waiting for the command to complete. It’s useful for tasks that aren’t required to be completed for other parts of the program, or running multiple instances of the same command at the same time, such as running a full backup of multiple databases to shorten execution time.
Now that we know how to chain commands, we can jump into another core feature of any programming language – variables.
Variables
Section titled “Variables”In Bash, there are two types of variables: global and local variables. Global variables are accessible throughout the whole time the script is running unless the variable is unset. Local variables are accessible only within a block of the script (for example, a defined function).
Whenever a script gets executed, it gets an existing set of variables from the currently running shell; this is called an environment. You can add new variables to the environment using the export command, and remove variables by using the use unset command. You can also add functions to the environment by using the declare - x command.
All parameters, regardless of whether they’re local or global, are prefixed with a dollar sign ($). So, if you have a variable named CARS (case-sensitive), to refer to it, you will need to write $CARS inside your script.
For variables, single or double quotes (or no quotes) matter. If you put a variable in a single quote, it won’t be expanded, and a variable name inside quotes will be treated as a literal string. Variables inside double quotes will be expanded, and it’s considered a safe way to refer to variables (and concatenate them, or glue them together) because if there is a space or other special character in a string, it won’t be significant for the script – that is, it won’t be executed.
Sometimes, you will need to concatenate multiple variables. You can do this using curly brackets ({}). For example, "${VAR1}${VAR2}" will expand to whatever you have VAR1 and VAR2 set to. In that context, you can also use curly brackets to cut or replace parts of the string. Here’s an example:
name="John"welcome_str="Hello ${name}"echo "${welcome_str%John}Jack"The preceding code will display Hello Jack instead of Hello John. The % operator will only remove characters from the end of the string. If you want to cut variables from the beginning of the string, you would use the # operator in the same way.
If you refer to a variable without any quotes, space inside the value of the variable may break the flow of the script and impede debugging, so we strongly suggest using either single or double quotes.
Parameters
Section titled “Parameters”There are two kinds of parameters we could use, but both are a special kind of variable, so each is prefixed with a dollar sign ($).
The first kind of parameters you need to be aware of are positional parameters – these are the parameters that are passed to your script or a function inside a script. All parameters are indexed starting with 1 until n, where n is the last parameter. You’ll refer to each of these parameters with $1 until $n. You’re probably wondering what will happen if you use $0.
$0 contains the name of your script, so it’s useful for generating documentation within a script, for example.
To refer to all available parameters starting from 1, you can use $@ (dollar sign, at).
Here are some other special parameters that are commonly used:
#: Number of positional parameters?: Exit code of the most recently executed foreground command$: Process ID of the shell
You are probably familiar with different types of loops as they are in other programming languages. You can find all of those in Bash, but with a slightly different syntax than you might be familiar with.
The most basic, a for loop, looks like this:
for variable_name in other_variable; do some_commands; doneThis variant of the for loop sets whatever element inside other_variable as a value of variable_name and executes some_commands for every element it finds. After it’s completed, it exits the loop with the status of the last executed command. The in other_variable part can be omitted – in that case, the for loop executes some_commands once for each positional parameter. The use of this parameter will look like this:
for variable_name; do some_commands; doneThe preceding for loop will run as many times as you added input variables for your function (or script in this case). You can refer to all positional parameters with $@.
The following is a for loop in a form known from C/C++:
for (( var1 ; var2 ; var3 )); do some_commands; doneHere’s an example use of this syntax:
for ((i=1; i<=5; i++)); do echo $i; doneThe first expression sets the i variable to 1, the second expression is a condition to be met for the loop to still run, and the final expression is incrementing the i variable by 1. Each loop run will display the next value set to the i variable.
The output of this command will look like this:
12345Another useful loop is a while loop, which runs as many times as needed until the condition is met (the command we pass to it exits with a success – it returns zero). Its counterpart is a loop called until, which will keep running so long as the command we pass to it returns a non-zero status:
while some_command; do some_command; doneuntil some_command; do some_command; doneYou can create an infinite loop by using a command that will always meet the condition, so for the while loop, it can be simply true.
The most commonly used blocks of commands are conditionals and are used with if statements. Let’s take a closer look.
Conditional execution – if statement
Section titled “Conditional execution – if statement”The if statement has the following syntax:
if test_commandthen executed_if_test_was_truefitest_command can be any command you can think of, but commonly, the test is wrapped between double or single square brackets. The difference between these two is the former is a system command called test (you can check its syntax by executing man test), while the latter is a Bash built-in and more powerful test.
The rule of thumb for putting variables between square brackets is using double quotes, so if a variable contains spaces, it won’t change the intention of our test:
if [[ -z "$SOME_VAR" ]]; then echo "Variable SOME_VAR is empty"fiThe -z test checks whether the $SOME_VAR variable is empty. It evaluates to true if the variable is empty and false if not.
The following are other commonly used tests:
-a: Logical AND-o: Logical OR-eq: Is equal to-ne: Is not equal to-gt or >: Is greater than-ge or >=: Is greater than or equal to-lt or <: Is less than-le or <=: Is less than or equal to= or ==: Is equal to!=: Is not equal to-z: String is null (its length is zero characters)-n: String is not null-e: File exists (directory, symlink, device file, or any other file in the filesystem)-f: File is a regular file (not a directory or device file)-d: File is a directory-hor-L: File is a symbolic link-r: File has read permission (for the user running the test)-w: File has write permission (for the user running the test)-x: File can be executed by the user that executed the script
Note that tests may behave differently when using a system test (single square brackets, [...]) rather than the built-in one (double square brackets, [[...]]).
The double equal comparison operator, while comparing strings when using globbing, will match the pattern or literal string, depending on whether you’ve quoted the pattern or not.
The following is an example of pattern matching if the string starts with w:
if [[ $variable == w* ]]; echo "Starts with w"fiWhen using a system test (a single square bracket) instead of a built-in one, the test will try to find whether the $ variable matches any of the filenames in the local directory (including those with spaces). This can lead to some unpredictable outcomes.
The following is an example of pattern matching if the string is w*:
if [[ $variable == "w*" ]]; echo "String is literally 'w*'"fiEquipped with this knowledge, we’re ready to start creating and running scripts. So, let’s jump right to it!
Understanding the backup script – first steps
Section titled “Understanding the backup script – first steps”Now that we know what a script can look like, we can start writing one. You can use your favorite console editor or IDE to do this. Let’s create an empty file named run_backups.sh and change its permissions so that they’re executable:
admin@myhome:~$ touch run_backups.sh && chmod +x run_backups.shadmin@myhome:~$ ls -l run_backups.sh-rwxr-xr-x 1 admin admin 0 Dec 1 15:56 run_backups.shIt’s an empty file, so we’ll need to add a basic database backup command and proceed from there. We won’t be covering granting this script access to a database. We will be backing up a PostgreSQL database and using the pg_dump tool for that purpose.
Let’s input a shebang line and a pg_dump command call in our base script:
#!/usr/bin/env bashpg_dump mydatabase > mydatabase.sqlTo execute this script, we’ll need to start the following command:
admin@myhome:~$ ./run_backups.shThe dot and slash indicate that we want to execute something that is located in a current directory, and its name is run_backups.sh. Without the initial dot-slash pair, the shell we’re running on (here, bash) would look into the PATH environment variable and would try to find our script in one of the directories listed there:
admin@myhome:~$ echo $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binAs you can see, it’s a list of directories delimited with a colon.
Now, let’s see what our Bash script does when executed:
admin@myhome:~$ ./run_backups.sh./run_backups.sh: line 3: pg_dump: command not foundUnless you already have pg_dump installed on your system, you will see this error. It means that Bash didn’t find the command we intended to run. It also displays the line where the error occurred. Also, an empty mydatabase.sql file was created.
Normally, we would proceed with creating a Docker image with all the tools we need, and a second one with a PostgreSQL database running. But since this will be covered in Chapter 8, let’s just proceed and install everything we need on a local machine. Assuming you’re on an Ubuntu or a Debian Linux machine, you want to run the following commands:
admin@myhome:~$ sudo apt-get updateGet:1 http://archive.ubuntu.com/ubuntu jammy InRelease [270 kB][Condensed for brevity]Get:18 http://archive.ubuntu.com/ubuntu jammy-backports/main amd64 Packages [3520 B]Fetched 24.9 MB in 6s (4016 kB/s)Reading package lists... Doneadmin@myhome:~$ sudo apt-get install postgresqlReading package lists... DoneBuilding dependency tree... DoneReading state information... DoneThe following additional packages will be installed: cron libbsd0 libcommon-sense-perl libedit2 libgdbm-compat4 libgdbm6 libicu70 libjson-perl libjson-xs-perl libldap-2.5-0 libldap-common libllvm14 libmd0 libperl5.34 libpopt0 libpq5 libreadline8[Condensed for brevity]Suggested packages: anacron checksecurity default-mta | mail-transport-agent gdbm-l10n libsasl2-modules-gssapi-mit | libsasl2-modules-gssapi-heimdal libsasl2-modules-ldap libsasl2-modules-otp libsasl2-modules-sql[Condensed for brevity]0 upgraded, 42 newly installed, 0 to remove and 2 not upgraded.Need to get 68.8 MB of archives.After this operation, 274 MB of additional disk space will be used.Do you want to continue? [Y/n] yAfter user confirmation, the database will be installed, configured, and started in the background. We’ve cut the further output for readability.
After installation, you might need an additional configuration change for the database so that you can connect to the database with another tool called psql, which is a console command that’s useful for connecting to PostgreSQL. In the /etc/postgresql/14/main/pg_hba.conf file, we have defined trust relationships and who can connect to the database using multiple mechanisms.
Find the following line:
local all postgres peerChange it to the following:
local all all trustAfter making this modification, you can restart the database with the following command:
admin@myhome:~$ sudo systemctl restart postgresql* Restarting PostgreSQL 14 database serverNow, you should be able to log in to the database and list all available databases:
admin@myhome:~$ psql -U postgres postgrespsql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1))Type "help" for help.postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges-----------+----------+----------+---------+---------+----------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | |postgres=CTc/postgres(3 rows)postgres=# \qadmin@myhome:~$After logging in, we list all available databases with \l (backslash, lowercase L) and quit the psql shell with \q (backslash, lowercase Q). Once this is set, we can get back to our script and try to run it again:
admin@myhome:~$ ./run_backups.shpg_dump: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "root" does not existThere’s no root role in PostgreSQL, which is an expected error at this point. We will need to use a different role to connect to the database. The default is postgres and the option to pass to pg_dump is -U, the same as what we used with psql. After updating it, our script will look like this:
#!/usr/bin/env bashpg_dump -U postgres mydatabase > mydatabase.sqlThe final step is to create a database and some actual data so that the output sql file won’t be empty. The following script will create a database named mydatabase and create two tables that contain random data:
CREATE DATABASE mydatabase;\c mydatabaseCREATE TABLE random_data AS SELECT data_series, md5(random()::text) from generate_series(1,100000) data_series;CREATE TABLE another_random AS SELECT data_series, md5(random()::text) from generate_series(1,100000) data_series;The CREATE DATABASE line is creating a database named mydatabase. The second line indicates we’re connecting to this new database. Two additional lines starting with CREATE TABLE are both creating tables and filling them with data using built-in PostgreSQL functions. Let’s break it down into two distinct queries – SELECT and CREATE:
SELECT data_series, md5(random()::text) from generate_series(1,100000) data_series;There are a few things going on here:
- The
generate_series()function is creating a series of integers starting from 1 up to 100,000 – this will generate all our records in a table - The
data_serieskeyword, just before a semicolon, names output from thegenerate_series()function, so it’s an actual field name in a table we intend to create - The
random()function is generating a value between 0 and 1 – that is, greater than or equal to 0 and less than 1 - The
::textafter therandom()function is converting output from this function into text - The
md5()function is taking the output fromrandom()::textand hashing it with anmd5algorithm, ensuring that we have a unique string and run as many times as thegenerate_series()function’s output amount will be (here, this is from 1 to 100,000) - Finally,
SELECT data_series, md5()is producing a table with two fields (data_seriesandmd5) with data generated by both functions
Now, getting back to CREATE TABLE, there’s a part called another_random AS – this will get the output from SELECT and create a table for us.
With this knowledge, we can create a sql script and execute it using psql:
admin@myhome:~$ psql -U postgres < create_db.sqlCREATE DATABASEYou are now connected to database "mydatabase" as user "postgres".To check whether we’ve created something and investigate the data we’ve created, again, we will need to use psql and the SELECT query on our new database:
admin@myhome:~$ psql (14.1)Type "help" for help.postgres=# \c mydatabaseYou are now connected to database "mydatabase" as user "postgres".mydatabase=# \dt List of relations Schema | Name | Type | Owner--------+----------------+-------+---------- public | another_random | table | postgres public | random_data | table | postgres(2 rows)mydatabase=# select * from random_data ; data_series | md5-------------+---------------------------------- 1 | 4c250205e8f6d5396167ec69e3436d21 2 | a5d562ccd600b3c4c70149361d3ab307 3 | 7d363fac3c83d35733566672c765317f 4 | 2fd7d594e6d972698038f88d790e9a35--More----More– at the end of the preceding output indicates there are more records to be shown. You can see more data by pressing the spacebar or quit by pressing Q on your keyboard.
Once you have created a database and filled it with some data, you can try to run our backup script again:
admin@myhome:~$ ./run_backup.shadmin@myhome:~$There are no errors, so we have probably created a full database dump with success:
admin@myhome:~$ ls -l mydatabase.sql-rw-r--r-- 1 root root 39978060 Dec 15 10:30 mydatabase.sqlThe output file isn’t empty; let’s see what’s inside:
admin@myhome:~$ head mydatabase.sql---- PostgreSQL database dump---- Dumped from database version 14.1-- Dumped by pg_dump version 14.1SET statement_timeout = 0;SET lock_timeout = 0;SET idle_in_transaction_session_timeout = 0;After some SET statements, you should also find CREATE TABLE and INSERT statements. I haven’t provided full output here as it would take up a lot of space.
In this section, we learned how to set up a testing environment for our script and made it possible for our script to create a database dump. In the next section, we’ll focus more on error handling and checking whether the backup was successful.
Handling errors and debugging
Section titled “Handling errors and debugging”While running our backup script, we can encounter several errors: access to the database might be blocked, the pg_dump process might get killed, we may be out of disk space, or any other error preventing us from completing a full database dump.
In any of those cases, we will need to catch the error and handle it gracefully.
Additionally, we might want to refactor the script to make it configurable, make use of functions, and debug the script. Debugging will prove very useful, especially when dealing with larger scripts.
Let’s dive right into it and start with adding a function:
#!/usr/bin/env bashfunction run_dump() { database_name=$1 pg_dump -U postgres $database_name > $database_name.sql}run_dump mydatabaseWe’ve added a run_dump function that takes one argument and sets a local variable called database_name with the content of this argument. It then uses this local variable to pass options to the pg_dump command.
This will immediately allow us to back up multiple databases by using a for loop, like so:
for dbname in mydatabase mydatabase2 mydatabase3; do run_dump $dbnamedoneThis loop will create a full dump of the databases: mydatabase, mydatabase2, and mydatabase3. Backups will be done one by one using this function. We can now put a list of the databases in a variable to make it more configurable. The current script will look like this:
#!/usr/bin/env bashdatabases="mydatabase"function run_dump() { database_name=$1 pg_dump -U postgres $database_name > $database_name.sql}for database in $databases; do run_dump "$database"doneNow, this backup script is becoming more complicated. We need to note a few things that will be happening now:
- If any of the backups should fail, the script will continue running
- If the backups fail due to
pg_dumpnot having access to the database, we will overwrite our previous database dump - We will be overwriting the dump file on every run
Several default settings are considered to be good practice to override in a script. One that would mitigate the first problem we’ve pointed out is aborting running when any command returns a value that’s different than zero (or true). This means the command finished running with an error. The option’s name is errexit and can we override it with the set command, a Bash built-in command. We could do this in two ways:
set -o errexitset -eHere are some other options we recommend using:
set -u: This treats any unset variable we try to use in a script as an errorset -o pipefail: When using chaining commands with a pipe, the exit status of this pipeline will be the status of the last command that finished with a non-zero status or zero (a success) if all commands exit successfullyset -Corset -o noclobber: If set, Bash won’t overwrite any existing file with the redirection commands (for example,>, which we’re using in our script)
An additional option that is extremely useful is set -x or set -o xtrace, which causes Bash to print every command before executing said command.
Let’s see how it works for a simple Bash script:
#!/usr/bin/env bashset -xecho "Hello!"Here’s the output of executing this script:
admin@myhome:~$ ./simple_script.sh+ echo 'Hello!'Hello!Let’s update our backup script with the recommended Bash settings:
#!/usr/bin/env bashset -uset -o pipefailset -Cdatabases="mydatabase"function run_dump() { database_name=$1 pg_dump -U postgres $database_name > $database_name.sql}for database in $databases; do run_dump "$database"doneNow, let’s get back to the console to test whether it’s still working as we expect:
admin@myhome:~$ ./run_backups.sh./run_backups.sh: line 12: mydatabase.sql: cannot overwrite existing fileWe’ve enabled the noclobber option and it has prevented us from overwriting previously made backups. We’ll need to rename or delete the old file before we can proceed. This time, let’s also enable the xtrace option to see what command script is being executed:
admin@myhome:~$ rm mydatabase.sqladmin@myhome:~$ bash -x ./run_backups.sh+ set -u+ set -o pipefail+ set -C+ databases=mydatabase+ for database in $databases+ run_dump mydatabase+ database_name=mydatabase+ pg_dump -U postgres mydatabaseTo mitigate the overwrite existing file error, we could do one of three things:
- Delete the previous file before attempting to run the backup, which would destroy the previous backup.
- Rename the previous backup file and add a current date suffix.
- Make sure that every time we run a script, the dump file has a different name, such as a current date. This would ensure we are keeping previous backups in case we need to get back to a version that’s earlier than the last full backup.
In this case, the most common solution would be the final one we’ve proposed – generate a different backup file name every time the backup runs. First, let’s try to get a timestamp with the local date and time in the YYYYMMDD_HHMM format, where we have the following options:
YYYY: The current year in a four-digit formatMM: The current month in a two-digit formatDD: The day of the month in a two-digit formatHH: The current hourMM: The current minute
We can achieve this by using the date command. By default, it will return the current date, day of the week, and the time zone:
admin@myhome:~$ dateFri Dec 16 14:51:34 UTC 2022To change the default output of this command, we’ll need to pass a date format string using formatting characters.
The most common formatting characters for the date command are as follows:
%Y: Year (for example, 2022)%m: Month (01-12)%B: Long month name (for example, January)%b: Short month name (for example, Jan)%d: Day of month (for example, 01-31, depending on how many days are in a certain month)%j: Day of year (for example, 001-366)%u: Day of week (1-7)%A: Full weekday name (for example, Friday)%a: Short weekday name (for example, Fri)%H: Hour (00-23)%I: Hour (01-12)%M: Minute (00-59)%S: Second (00-59)%D: Display date as mm/dd/yy
To format the date in a format we want, we’ll need to use formatting characters, %Y%m%d_%H%M, and pass it to the date command for interpretation:
admin@myhome:~$ date +"%Y%m%d_%H%M"20221216_1504To pass the output string to a variable in our script, we’ll need to run the date in a subshell (a Bash process executed by our Bash script):
timestamp=$(date +"%Y%m%d_%H%M")Let’s put it inside our script and use a timestamp variable to generate an output filename:
#!/usr/bin/env bashset -uset -o pipefailset -Ctimestamp=$(date +"%Yum'd_%H%M")databases="mydatabase"function run_dump() { database_name="$1" pg_dump -U postgres "$database_name" > "${database_name}_${timestamp}".sql}for database in $databases; do run_dump "$database"doneIf you have spotted curly braces between variables in a pg_dump line, you’re probably wondering why we need them. We use curly braces to make sure that the variable name will be correct when we expand a variable to a string. In our case, we’re preventing Bash from trying to search for a variable name, $database_name_, that doesn’t exist.
Now, each time we run our backup script, it will try to create a new file with the current date and time of the backup start time. If we’re running this script every day, the number of files will increase over time and will eventually fill our disk space. So, we’ll also need our script to remove old backups – say, 14 days and older.
We can achieve this by using the find command. Let’s find all files beginning with a database name, followed by an underscore, and ending with.sql that are older than 14 days:
admin@myhome:~$ find . -name "mydatabase_*.sql" -type f -mtime +14./mydatabase_20221107.sqlThe find command has a peculiar syntax that is a bit different than other command-line tools have, so let’s describe what each option means:
.(a dot): This is a directory where we want to search for our files. Dot means a current directory.-name: This option can take a full string or wildcards such as*or?and it’s looking for filenames in this case. It’s case-sensitive. If we’re not certain that the file or directory we’re looking for is uppercase or lowercase, we could use the-inameoption instead.-type f: This indicates we’re looking for a regular file. Other options are as follows:d: Directoryl: Symbolic links: A socket filep: FIFO fileb: Block devicec: A character device
-mtime +14: The modification time of this file should be older than 14 days. This option can also take other units (seconds, -s, weeks, -w, hours, -h, and days, -d– it’s the default if no unit is given).
To delete found files, we have at least two options: the -delete option or the rm command via an -exec find option. Let’s see how this looks in both cases:
admin@myhome:~$ find . -name "mydatabase_*.sql" -type f -mtime +14 -deleteadmin@myhome:~$ find . -name "mydatabase_*.sql" -type f -mtime +14 -exec rm -- {} \;- In this case, a safer choice would be to use
-execdirinstead of-exec. The difference is subtle but important:-execwill not be executed in the same directory where the found file is located, but-execdirwill, which makes it a safer option in edge cases.
Let’s deconstruct what we have after the - exec option:
rm: This is a CLI tool for removing files or directories.--(double dash): This indicates that it will take arguments fromstdin, or the output of thefindcommand.{}: This will substitute for a filename we’ve found.\;(backslash, semicolon): This will take multiple commands to be executed by-exec. A backslash is an escape character that prevents this semicolon from being interpreted as a separator for the next command. Thefindutility uses;or+to terminate the shell commands, so we could note it as";",\+, or+(without quotes).- The
-deleteoption is good for removing files, but it always returnstrue, so it will fail silently if, for example, our script doesn’t have permission to remove any files. It’s relatively safe to use it in our script, so we’ll go ahead with it.
Now, let’s embed this into our script and see the final iteration of it:
#!/usr/bin/env bashset -uset -o pipefailset -Ctimestamp=$(date +"%Y%m%d_%H%M")databases="mydatabase"function cleanup_old_backups() { database_name="$1" find . -type f -name "${database_name}_*.sql" -mtime +14 -delete}function run_dump() { database_name="$1" pg_dump -U postgres "$database_name" > "${database_name}_${timestamp}".sql}for database in $databases; do cleanup_old_backups "$database" run_dump "$database"doneHere, we’ve added a function called cleanup_old_backups that will run before creating a new dump to free some space for fresh files. We’re calling this function inside a for loop just before run_dump. This script can be run automatically by a cron daemon or systemd cron service; we’ll cover this in more detail in Chapter 5, Managing Services in Linux.
In this section, we learned about the recommended options to enable in shell scripts and how to enable debugging options. We know now how to create functions and loops. Additionally, we partially touched on PostgreSQL and how to create a testing database.
The next chapter will take us deeper into various Linux services and how to manage them using init and systemd.
Summary
Section titled “Summary”Shell scripting is a very common way of automating periodically running tasks in a Linux system. Sometimes, it evolves to a bigger system chained together with multiple Bash scripts and Python programs to complete complex tasks using multiple smaller tasks that do one thing at the same time in a very reliable way.
In modern systems, you will probably see as much Bash as Python scripts.
In this chapter, we learned how to create an executable script, as well as how to create a simple backup script that handles errors and generates a new filename on each run. We also added a function that removes old backups so that we can avoid filling the disk space. Additionally, as a side effect, we learned how to create a new PostgreSQL database and allow access to it from a local system.
In the next chapter, we’ll learn how to create Linux services and how to manage them.
Exercises
Section titled “Exercises”Try out the following exercises to test your knowledge of this chapter:
- Write a function that will list all databases and feed that list to the for loop we’ve created.
- Change a date timestamp into another format of your choosing.
- Catch any errors the
findfunction could return (for example, it couldn’t delete a file).