Linux Shell Scripting
local graph
Chapter 8 — Linux Shell Scripting
Section titled “Chapter 8 — Linux Shell Scripting”Knowing how to use the basics of Linux shell programming and the command-line interface (CLI) is essential for a modern-day Linux professional.
In this chapter, you will learn how to use the Linux shell’s programming capabilities to automate different tasks in Linux. You will learn about the structure of a basic Linux shell script and how it is organized and executed. We’ll explore most of the commands already available to you from the previous chapters, especially the ones for working with files and directories and input and output redirection. Along the way, we’ll introduce you to writing scripts, the structure and complexity of shell programming, and how to use specialized tools such as sed and gawk. We hope that by the end of this chapter, you’ll be comfortable using scripts in your day-to-day workflow and be ready for future, more advanced explorations.
We’re going to cover the following main topics:
- Introducing shell features
- The structure of a shell script
- Decisions, loops, variables, arrays, and functions
- Using
sedand (g)awk
Technical requirements
Section titled “Technical requirements”This chapter requires a working installation of a standard Linux distribution, on either server, desktop, PC, or virtual machine (VM). Our examples and case studies will use mainly Ubuntu/Debian and RHEL/Fedora platforms, but the commands and examples that will be explored are equally suitable for other Linux distributions, such as openSUSE/SLE.
Exploring the Linux shell
Section titled “Exploring the Linux shell”Back in Chapter 2, The Linux Shell and Filesystem, we introduced you to the shell by exploring the available virtual consoles, command types, and the filesystem. This gave you a fair foundation for what we are about to explore in this chapter. By now, with everything we have been showing you in this book, you are already well versed in using the command line; you know some of the most common and useful commands available in Linux as we explored file operations, package, user, and disk management, all the way up to network administration. All this knowledge will eventually be put to use in this chapter, where we will explore advanced shell features, shell variables, regular expressions, and how to take advantage of the powerful programming and automation features of the Bash shell.
In the next section, we will begin discovering the advanced features of the shell.
Bash shell features
Section titled “Bash shell features”The shell not only runs commands but also has many more features that make a system administrator’s life more comfortable while at the command line. Some of these features include the use of wildcards and metacharacters, brace expansion, and variables. Apart from these, you will learn about the shell’s PATH and aliases.
Before we proceed, let’s dig into a little history about the standards the shell is based on. Back in the day, when UNIX emerged as an operating system, the need for a standard to oversee different variants appeared. Thus, the Institute of Electrical and Electronics Engineers (IEEE) created the Portable Operating System Interface (POSIX) as a family of different standards that were meant to assure compatibility between operating systems. Therefore, UNIX and Linux, as well as macOS (based on Darwin, the kernel of macOS derived from UNIX), AIX, HP-UX, and Oracle Solaris, are POSIX compliant. POSIX has different standards for the C language API, file format definitions, directory structures, environment variables definitions, locale specifications, character sets, and regular expressions.
With this short history lesson under our belts, let’s proceed. In the next section, we will show you how to use shell wildcards and metacharacters.
Wildcards and metacharacters
Section titled “Wildcards and metacharacters”In Linux, wildcards are used to match filenames. There are three main types of wildcards:
- Asterisk (
*): This is used to match any string of none or more characters - Question mark (
?): This is used to match a single character - Brackets (
[ ]): This is used to match any of the characters inside brackets
Metacharacters are special characters that are used in Linux and any Unix-based system. These metacharacters are as follows:

Figure 8.1 – Metacharacter list
Let’s look at two examples that use metacharacters for command substitution. We use the output of one command inside another command. This can be done in two ways, as shown in the following figure:

Figure 8.2 – Example of command execution and substitution
The purpose of the preceding example is to show you how command substitution works in the shell, but perhaps we should explain further what the commands used do. We used two commands: echo and date. We used the output of the date command inside the output of the echo command. The echo command is one of the simplest commands in Linux as it prints the message between the quotes to the standard output. In our case, the message also consists of the date command, which outputs the current date of the system, in the format shown.
You can also combine two or more commands, and to do this in Linux, we use the pipe. The pipe sends the output of the first command that was used as the input for the second command, and so forth, depending on how many pipes you use.
In the following example, we’re using the ls -l /etc command to do a long listing of the contents of the /etc directory; we will pipe this to the less command. Use it as shown in the following code:
ls -l /etc | lessThe less command will show one display at a time, allowing you to see all the contents. You can use the arrow keys or the page up and page down keys to navigate through the output and see all the contents of the / etc directory.
The pipe and command substitution will be very useful, especially when you’re working with complex commands or when scripting, as you will see later in this chapter when you learn how to create and use scripts.
Now, let’s execute some commands in a sequence. After that, we will use metacharacters to group commands and redirect the output to a file. All this is shown in the following screenshot:

Figure 8.3 – Example of command sequence execution
As you can see in the preceding output, the two commands that were executed on the first line can easily be grouped using brackets, and their output can be redirected to a file.
We used three types of metacharacters – the command execution sequence (;), the brackets for grouping commands in the execution sequence, and the output redirection (>) to redirect the output to a file. The file did not exist initially as it was created only when the command was executed. The last command we used was the cat command, which concatenates the contents of the newly created file.
The first two commands that were used were who, which prints information about the currently logged-in users to the standard output, and pwd, which prints the present working directory as the location we are in inside the filesystem. In the following section, we will show you how to use brace expansion with the shell.
Brace expansion
Section titled “Brace expansion”Curly brackets can also be used to expand the arguments of a command. Braces are not just limited to filenames, unlike a wildcard. They work with any type of string. Inside these braces, you can use a single string, a sequence, or several strings separated by commas.
In this section, we will show you some examples of using this type of expansion. First, we will use brace expansion to delete two files from one directory. Second, we will show you how to create multiple new files using brace expansion. Let’s say that we have two files named report and new-report inside our present working directory and we want to delete them both at once. We can use the following command:
rm {report,new-report}To create multiple files (five of them, for example) that share parts of their name, as in file1, file2, … filen, we can use the following command:
touch file{1..5}The following screenshot shows the output of both these commands:

Figure 8.4 – Examples of using brace expansion
Important note
Brace expansion is a powerful tool that adds flexibility and power to any system administrator’s workflow. They will prove very useful when learning how to script, for example.
Now that we’ve created those files, it should be really easy for you to figure out how to use brace expansion to delete multiple files at once. Type the following command into your console and see what happens:
rm file{1..5}It will delete all five files we created previously. Use the ls command to see the contents of the present working directory.
In the next section, we will talk about shell command aliases, what they are, and how to use them.
The shell’s aliases
Section titled “The shell’s aliases”The Linux shell supports aliases, which are a very convenient way to create short commands as aliases for longer ones. For example, in Ubuntu, there is a predefined alias called ll that is shorthand for ls -alF. You can define your own aliases too. You can make them temporary or permanent, similar to variables. In the following example, we changed the alias for the ll command:

Figure 8.5 – Changing the alias of a command
This modification is only temporary, and it will revert to the default version after reboot or shell restart. If you want to make it permanent, you should edit the ~/.bashrc file and add the aliases you created previously inside the file. To do this, open the file with your preferred text editor and add the lines you used in the Terminal to the file. Save the file and execute it. Also, a better practice would be to add those lines to a new file called .bash_aliases. You can view the default contents of .bashrc for more information on how to use aliases.
Important note
The .bashrc file is a hidden script file that consists of different Terminal session configurations. Also, the file can contain different functions that can help the user overcome repetitive tasks. It is automatically executed when the user logs in, but it can also be manually executed by using the source .``bashrc command.
In the next section, we will show you what shell variables are and how to use them.
Bash shell variables
Section titled “Bash shell variables”The Bash shell uses different types of variables, in the same way you would use them in any programming language. The Bash shell has some built-in variables and indirect variables and offers the possibility to define your own variables as well.
Linux has two major types of shell variables: global and local variables. They are generally identical for every Linux distribution out there, with some exceptions. You will need to consult your distribution’s documentation for any specific modifications to the environment variables.
We will walk you through the most widely used variables in Linux, starting with the built-in ones.
Built-in shell variables
Section titled “Built-in shell variables”Here is a short list of some of the standard built-in variables:
HOME: The user’s home directory (for example,/home/packt)LOGNAME: The user’s login name (for example,packt)PWD: The shell’s current working directoryOLDPWD: The shell’s previous working directoryPATH: The shell’s search path (list of directories separated by colons)SHELL: The path to the shellUSER: The user’s login nameTERM: The type of the Terminal
To call a variable while in the shell, all you have to do is place a dollar sign, $, in front of the variable’s name. Here is a short example that shows how to use the variables that we just listed:

Figure 8.6 – Variable calling from the shell
You can also assign your own shell variables, as in the following example. Here, we’re assigning the sysadmin string to a new variable called MYVAR and then printing it to standard output:
MYVAR=sysadmin; echo $MYVARThe variables listed at the beginning of this section are just a part of all the variables available by default inside the shell. To see all the shell variables, use the printenv command. If the list is too long, you can redirect it to a file. In the following example, your variables list is inside the shell_variables file, and you can see it by concatenating or by editing inside a text editor such as Vim:
printenv > ~/shell_variablesHere, we use the tilde symbol (~) to specify the logged-in user’s home directory. The shell’s variables are only available inside the shell. If you want some variables to be known to other programs that are run by the shell, you must export them by using the export command. Once a variable is exported from the shell, it is known as an environment variable.
The shell’s search path
Section titled “The shell’s search path”The PATH variable is an essential one in Linux. It helps the shell know where all the programs are located. When you enter a command into your Bash shell, it first has to search for that command through the Linux filesystem. Some directories are already listed inside the PATH variable, but you can also add new ones. Your addition can be temporary or permanent, depending on how you do it. To make a directory’s path available temporarily, simply add it to the PATH variable. In the following example, we’re adding the /home/packt directory to PATH:

Figure 8.7 – Adding a new location to PATH
To make any changes permanent, we must modify the PATH variable inside a file called ~/.bash_profile or ~/.bashrc.
Important note
Some distributions, such as openSUSE, add an extra bin directory inside the user’s home directory. This is a place where you can put files that you want the shell to execute – for example, script files.
The shell’s $PATH variable is important, especially when using scripts, as you will preferably have to create scripts inside a directory that is known by the shell. In the next section, we will show you how to create your first Bash scripts.
Basics of shell scripting
Section titled “Basics of shell scripting”We have already covered important aspects of the Linux command line, shell variables, wildcards, and metacharacters. Now, we will start exploring what scripts are, how to create them, and how to use them in a Linux CLI. We will not use the graphical user interface, only the CLI, which we primarily used in our previous chapters. Let’s start with some basic, but important, concepts about shell scripting.
First, let’s learn what a script is. If we were to check the meaning of the term in a dictionary, the answer would be that a script is a series of instructions that are executed by a computer, mainly to automate a specific task. Instructions can easily be assimilated as commands too. Thus, a series of commands executed together by the shell can be considered a script. This is a very basic script, but it is a script. Let’s look at how we can create a script file.
Creating a shell script file
Section titled “Creating a shell script file”The most appropriate way to write scripts is to create them in the form of a file, called a shell script file. In Linux, these types of files should use the .sh extension for clarity. However, this is not obligatory, because in Linux, files don’t use extensions, unlike in Windows. The distinctive characteristic that makes a file considered a script is the very first line of text inside that file. In the case of a Bash shell script, this line is in the following format:
#!/bin/bashWhen the file is opened and executed, the first line tells the shell’s interpreter that it is dealing with a script file that, in our case, will be run by the Bash shell. If you are using a different shell, this first line will point to it. The use of the hashtag (#) inside a shell script file denotes a commented line, except for this very first line, where it is used, combined with the exclamation mark (!), to point to the shell’s interpreter. The #! combination is also called the shebang.
Let’s create a basic script file. We will use the following code:
#!/bin/bashwhoamiwhodateuptimeHere, we used four different commands in our first, basic script. We used a separate line for each command, but there is another way to write it: by putting all commands on the same line and using semicolons to separate them. However, for clarity, it is useful to use different lines.
Now that we have our first script, let’s run it. We created the script file inside our home directory under the name basic-script.sh. Let’s try and run it by simply invoking its name at the command line:
$ basic-script.shWe will be prompted with an error, as shown in the following screenshot:

Figure 8.8 – Error upon running the new script
You might be wondering why we get this error. It is because the shell does not know about your script. It cannot find it inside its PATH variable. As you might remember from the previous section, PATH is a variable that the shell uses to find the location of specific files to run. To overcome this error, we have two options:
- We can add the directory in which our script resides to the shell’s path
- We can use a relative or absolute path when we invoke the script at the command line
We will use the second method as it is more convenient. However, you can use the first method as a good practice exercise and try to add your directory’s location to the shell’s PATH variable. Let’s invoke the script file with its location:
$ ./basic-script.shWe will get another error, this time a different one, saying Permission denied. This is because we do not have permission to execute the file. When we created the file inside our Ubuntu machine, it only got read and write permissions for the file’s owner and its group because of the default umask value. To change that, we will need to make the file executable by using the following command:
$ chmod u+x basic-script.shOnce we’ve set the executable permissions on the file, we can run it again, and this time, the script will be executed. The output will show that every command inside our script was executed:

Figure 8.9 – Running an executable script file
As shown in the previous screenshot, the script was executed, and the output showed the result of each command inside. On the first line, we have the username (the output of the whoami command), on the second line, we have information about the logged-in users (the output of the who command), on the third line, we have information about the current date (the output of the date command), and on the last line, we have information about the current session (the output of the uptime command).
Important note
As a general rule, when writing scripts, we advise you to use as many comments as possible to detail each variable and parameter you choose. This is considered a good programming practice, which will make your code writing more enjoyable and relevant. Documenting your coding steps will make your scripts easier to read at a later time, both by yourself and by anyone else who might come across your code. We don’t use many comments in the examples used in this book, but this is due to constraints regarding page count. Nevertheless, we encourage you to use them.
With that, you know how to create a shell script file and how to execute it. Let’s proceed to more advanced topics now. In the next section, we will show you how to use variables in your scripts.
Variables in shell scripts
Section titled “Variables in shell scripts”We introduced you to variables at the beginning of this chapter. Now, it is time to learn how to use them inside a script. To recap, let’s see what kind of variables are used in Linux. We have environment variables, which are available from the shell, and user-defined variables, which are created by the users and are not directly available from the shell. These two types of variables can also be used inside scripts. You can see a complete list of environment variables in your system by using the printenv and/or set commands. We listed some of the most commonly used variables in the Built-in shell variables section earlier in this chapter.
Understanding naming conventions
Section titled “Understanding naming conventions”Inside the Linux shell, the system’s environment variables use only uppercase letters. Thus, the relevant naming considerations should be applied when creating user-specified variables. In this regard, there is not one single naming convention that applies. But you should take into consideration that the names of variables are case-sensitive and should be up to 20 characters in length. The way to assign a value to a variable is by using the equals (=) sign.
If you plan on using only uppercase letters in the names of your variables, you should consider the disastrous effects this might have, considering that the environment variables only use uppercase letters. We would advise you to consider one of the following rules when creating variable names inside your shell:
- Use only lowercase letters, underscores, and numbers
- Capitalize the first letter of a word in the variable name
Important note
When considering name length, try not to use very long names; instead, use succinct and relevant names or abbreviations. This will make your script easier to read and understand.
Now, let’s learn how to define and use our first variables inside a shell. We will explore this in the next section.
Defining and using variables
Section titled “Defining and using variables”Let’s create a new file called user-script.sh that will show relevant user information by using environment variables. After we create the file and enter the relevant code, we will make it executable and then we will run it. The following are the relevant commands:

Figure 8.10 – Using environment variables in a script
In the preceding figure, we used two different ways to show information with the echo command. When we used double quotes to show information, the environment variable was used inside the quoted string, and its value was displayed in the output. Keep in mind that when using single quotes, the value of the variable will not be passed through to the shell’s interpreter. We used four different environment variables to show information about the user. Those variables were UID, USER, HOME, and BASH. This is a very basic and straightforward way to use shell variables inside scripts.
You can also use your own variables, not just the ones that are provided by the shell. A very useful feature of the shell’s interpreter is that it can automatically determine the data type a variable is using. You should also know that the values of variables defined inside a shell script are only active so long as the shell is running, and they will be lost afterward. Let’s create a new shell script and use our own variables this time. The following is the output:

Figure 8.11 – A basic script using user-defined variables
Here, we created a file called user-variables.sh and defined two variables, one called value, which we gave a value of 25, and another variable called product, with a value of Shirt. When we called the variables inside the echo command, we used the same callout sign as for environment variables.
Now that you know how to name, define, and use a variable, let’s continue to more advanced topics. In the next section, we will show you how to use mathematical expressions inside your shell scripts.
Using mathematical expressions in shell scripts
Section titled “Using mathematical expressions in shell scripts”The shell is a programming language, so it has built-in features to work with numbers. The Bash shell provides the expr command, which is used for different mathematical operations. To learn about all the operations that are supported, please visit the internal manual page for the expr command, as we will not provide them fully here:
man exprHowever, we will show you how to use some of the operations that the expr command provides. Keep in mind that, as the manual says, you will need to escape (by using the backslash character, \) some of the characters used by the expr command, as they will be misinterpreted by the shell. Let’s create a new script file and do some basic mathematical operations. Our new file is called math.sh and can be created using the following code:

Figure 8.12 – Using the expr command inside scripts
Besides the expr command, we can also use square brackets as a much simpler variant for mathematical operations. Let’s modify the preceding script and replace the expr command:

Figure 8.13 – Using square brackets for math operations
As shown in the previous example, we use integer values. You can try and use a floating-point value for the vat variable, for example, and you will see that an error will be displayed when running the script. This is because the shell only supports integer arithmetic operations. There are workarounds to overcome this limitation, and the most feasible is by using the Bash calculator, or the bc command.
Important note
If you want to have full support for floating-point operations inside your shell, you might want to consider using the Z shell (Zsh). It is installed by default in some Linux distributions (Manjaro and Kali Linux) and on macOS. You can also install it in your distribution if you like.
Let’s see how we can use the bc command inside our math.sh script. We will change the code as follows:

Figure 8.14 – Using the bc command for floating-point operations
In the preceding example, we assigned a floating-point value to the vat variable and used the bc command to calculate a floating-point total. We can use the bc command inside a variable like so:
var=$(echo "option; expression" | bc)The option value provides options for bc to use. In our case, we used a variable called decs (an arbitrary name we chose) to specify the number of decimals we would like to provide. The expression parameter specifies the operation we used, which in our case was addition. We piped the output of the echo command to the bc command and the result was assigned to the var variable.
Creating Bash shell scripts is more than doing math operations or giving a sequence of consecutive shell commands. Sometimes, decisions need to be made inside the shell, depending on the input provided and the output expected. This is where specific programming structures intervene. We will walk you through all of them in the next section.
Using programming structures
Section titled “Using programming structures”In this section, we will show you how to use conditional and looping statements. They can prove invaluable when creating advanced shell scripts. We will also show you how to use arrays, how input reading is used inside scripts, and how to format and print data for the output.
Using arrays in Bash
Section titled “Using arrays in Bash”We showed you how to use variables in previous sections. Now, it is time to step up our game and show you how to make use of arrays, a more complex form of variable. Let’s say that we need to work with multiple variables that may store similar information, such as filenames. Instead of using multiple variables in the form of filename1, filename2, filename3 … filenameN, we can create an array that will hold all the filenames. If you know other programming languages, arrays may already be familiar to you. But if you don’t know any other programming languages, fear not, as Bash has a facile way of using arrays.
Let’s start with an easy example. Let’s say we have to work with different usernames. Instead of using different variables for each username, we can use an indexed array:
usernames=("paul" "janet" "mike" "john" "anna" "martha")The elements inside an array start from index number 0 (zero). This is important to remember when we need to access the contents of the array. If we would like to access the third element from the usernames array (the "mike" string), we must use the following code:
echo ${usernames[2]}The output will be mike (without quotes). To print out the entire array, use the following code:
echo ${usernames[*]} or echo ${usernames[@]}To print out the size of the array, as in the number of elements, use the following code:
echo ${#usernames[@]} or echo ${#usernames[*]}In our case, we have six elements inside, and the output will be 6.
Let’s say we need to add a new username ("alex") to the array. There are different ways to add it. If we just want to add it with no specified position from the beginning, we can use the following code:
usernames+=("alex")The new username will be appended at the end of the array. At this point, the array contains unordered names, and we will need to arrange them in alphabetical order. We will cover this in the Using looping statements section, after which we will teach you about output formatting and different conditional and looping statements.
Alternatively, we can add a new element ("zack", for example) at a specific position inside the array (let’s say position 2) by using the following code:
usernames[1]="zack"So far, we’ve only used strings inside arrays as an example. You can also use integers for indexed arrays. The built-in command to create an array is declare. To create an indexed array, you can use the following command:
declare -a array_nameYou can also create associative arrays using the following command:
declare -A array_nameAssociative arrays are based on key-value pairs of elements. The following is an example of an associative array declaration:
declare -A linux_distros=( [KDE]="openSUSE" [GNOME]="Fedora" [Xfce]="Debian" [Cinnamon]="Mint" )Presented inside square brackets are the keys that are used to map the values. Inside double quotes, we have the values. To print the values, you can use the same command you used for indexed arrays:
echo ${linux_distros[@]}To print the keys, use the following command:
echo ${!linux_distros[@]}The main difference between indexed and associative arrays is that indexed arrays are based on index value, where each element has a specific index position inside the array, whereas associative arrays use specific keys to map the values.
Arrays are important data structures inside Bash and we will make use of them later in this chapter when we discuss looping statements. But first, let’s learn how to read input data inside a script, and how to format output data. In the next section, we will show you how to read data from standard input.
Reading input data
Section titled “Reading input data”By default, the shell reads the input data from the standard input, which is the keyboard. To read from the standard input, you can use the read command. This command reads all input data provided until a new line is provided. This happens when you press the Enter key on your keyboard.
With the read command, you can provide one or more variables. If you use more variables, each word provided through standard input will be assigned to a variable. The following is an example:

Figure 8.15 – Using the read command for standard input
In the preceding screenshot, we used the read command with four variables called a, b, c, and d. When we first introduced the data, we only provided a value for the first variable, meaning that we hit Enter after entering the first word from the keyboard. Thus, we had only one value for a and no value for the others. When we used the read command for the second time, we provided values for every variable, thus hitting Enter after the word Thursday. This way, each variable received a relevant value. The read command has several options available, but you will have to read the manual to learn about them in detail. Similar to providing values from the standard input, the read command can receive input from a file by using redirection. For example, if we have a file called week-days, we can redirect its content to the read command:

Figure 8.16 – Using read with file redirection
The read command is used for input reading when creating scripts. We showed you how to use the command on the command line, but we will come back to it later in this chapter when we talk about more advanced scripts. In the following section, we will introduce you to output data formats.
Formatting output data
Section titled “Formatting output data”In Linux, the standard output is directed by default to the monitor. For this task, you will have two commands you can use. One of them is the echo command, which we’ve used quite extensively in this book. The other command is called printf, and we will cover its use in this section.
The printf command is similar to the one used in the C programming language. A quick manual search for the printf command will show us the form in which it should be used:
printf FORMAT [ARGUMENT] …All the arguments of the command are printed according to the format string provided. The format controls can have normal characters or escape sequences, containing backslash and letters. These escape sequences are clearly presented in the available manual. Briefly, some widely used sequences are as follows:
\b: Backspace\e: Escape\f: Form feed\n: New line\r: Carriage return\t: Horizontal tab\v: Vertical tab
When using a backslash with printf, it should be escaped from the shell by using double quotes or another backslash. For more details on this, please refer to the manual.
Besides escape sequences, the printf command has format specifiers. Here are some details about what some of these format specifiers represent:
%s: This is a string specifier and it’s used for basic string output%b: This is a string specifier that allows escape sequence interpretation%d: This is an integer specifier that’s used for integral values%f: This is similar to the integer specifier, but it’s used for floating-point values%x: This is used for the hexadecimal values of integers and output padding
Now that you know the basics of the printf command, let’s look at some examples of how to use it.
In the following figure, we’re using printf format specifiers to show you the difference between using them and not using them:

Figure 8.17 – Basic usage of the printf command
As shown here, when using the default setting, printf prints the string inside the double quotes but without a new line at the end. When using the %s format specifier, the command prints the strings provided as arguments and interprets them as characters – in our case, the strings between double quotes. Using \n will create a new line after each string.
Let’s use the printf command inside a script now. The following is an example of printf using the %s format specifier. Notice that we use the command using single quotes since the output is similar to when using double quotes:

Figure 8.18 – Using printf inside a script
The preceding figure shows a script that reads two variables from the standard input device and then shows both variables to the standard output (the monitor). We used the string specifier (%s) and the new line escape sequence (\n). Now, let’s dig deeper into formatting output. In the following examples, we’re using the new tab escape sequence (\t) together with the newline escape sequence (\n) and the string specifier. Take a look at the following figure and see how formatting works:

Figure 8.19 – Using tab and newline escape sequences
The example we just showed you is using escape sequences to mimic table formatting for the output. We can do this by using a script with more complex specifiers than the ones already used. In the following example, we’re using the string (%s), integer (%d), and floating (%f) specifiers to format a table output:

Figure 8.20 – Using complex specifiers and escape sequences for table formatting
Let’s detail our format-output.sh script. We have a variable called separator that’s used to print out the graphical border between the header and the contents. Then, we have the header and format variables, each using specifiers and sequences for formatting specifics. header starts with a new line (\n), followed by a string specifier with a length of 10 characters wide aligned to the left (%-10s), followed by eight characters wide aligned to the right (%8s), 10 characters wide aligned to the right (%10s), and 11 characters wide aligned to the right (%11s) with a new line at the end (\n). The format variable is used to format the contents of the table by using two string columns (using the %s specifier), one integer (%d), and one floating-point (%f) specifier. The integer value is used for the product ID and the floating-point value is used for the price. We use the %08d format specifier to print the ID, which means that the output will be 8 characters wide. The 0 character in front indicates that any empty spaces will be filled with zeros. This ensures that even when the ID number has less than eight digits, the remaining width will be padded with zeros to maintain the desired width of eight characters. The result is shown in the lower part of the preceding screenshot, where we have a table with products, their IDs, placement, and prices.
Thus, printf is a very versatile and powerful tool that can be used with great results insider your scripts. Now that you know the basic tools for input and output data formatting for Bash scripting, let’s proceed to other useful and important structures that can be used.
In the next section, we will cover exit statuses.
Understanding exit statuses and testing structures
Section titled “Understanding exit statuses and testing structures”To use conditional and looping statements, we need to understand the exit status of a command. Usually, when a statement is running, the given condition is checked and tested so that we can see the validity of the command. The status of a command is stored inside a special parameter that has the following form: $?. The question mark is the place of an integer that will give the status of the command. For example, if the command’s execution was successful, then the value of the question mark will be 0 (zero) and the parameter will show $0. If the command’s execution was not successful, the question mark can have any value starting from 1 to 255. Most regularly, the error number is 1, so the parameter will be $1. These are also called exit codes.
Alongside exit codes, testing structures are also important for conditional and looping statements in Bash. These testing structures are usually the building blocks for the aforementioned statements. They are considered shell’s keywords and are represented like so:
[[ ]]: Double square brackets are used to test the true or false status of a command; it can perform operations on regular expressions too(( )): Double brackets are used for arithmetic operationstest: This keyword is used to evaluate expressions such as strings, integers, and file properties
Important note
The syntax of Bash requires spaces to be used before and after brackets – for example, [ ``operation ].
In conditional statements, some other types of operators are used for testing. Let’s take a look at some of the most commonly used conditional operators for integer tests:
-eg: The equality check operator-ne: The inequality check operator-lt: The less than operator-le: The less than or equal to operator-gt: The greater than operator-ge: The greater than or equal operator
In addition, there are argument operators in Linux shell scripting. The $0 variable represents the command used to run the script, while $1 through $n represents the first through n th arguments passed to the command. For example, $1 refers to the first argument, $2 refers to the second argument, and so on, where $n represents the n th argument of the command.
Besides the operators shown in this section, basic mathematical operators are also currently used in conditional statements.
There are also testing structures for strings:
=: Tests if strings are identical (==is also accepted)!=: Tests if strings are NOT identical\<and\>: Less than and greater are accepted for string comparison, but they must be escaped (we already used the backslash character)
There are also testing operators for file types, which are in the form of options:
-f: Tests for a regular file-d: Tests for a directory-hor-L: Tests for a symbolic link-e: Testing for a file’s existence
Here are some other operators that are used for testing:
-a: The logical AND-o: The logical OR-z: To check if an input string was entered
Testing operators are complex and useful, so it’s very important to learn them.
In the next section, we will cover Bash conditional statements.
Using conditional if statements
Section titled “Using conditional if statements”Just like in any other programming language, Bash has conditional execution statements, such as if-then-fi, if-then-else-fi, and nested if, and conditional operators such as && (AND) and || (OR). We will show you how to use them in this section.
We will present the if statement in all its appearances (if-then, if-then-else, and nested if) in this section:
- In its most common form, the
if-then-fistatement has theThis Bashif [condition]thencommandsfiifstatement is runningconditionafter theifkeyword. If the command is completed successfully, meaning it has an exit status of zero, then it will run the commands that are listed after thethenkeyword. - The
if-then-else-fistatement is similar toif-thenand has theSimilar to the simplerif [condition]thencommandselsecommandsfiif-thenstatement,conditionis run, and depending on its exit status, the results are different. If it completes successfully, the commands after thethenkeyword are executed, but if there is another exit status (non-zero), the commands after theelsekeyword are executed. This gives more options and alternatives, based on the result of the condition. There are situations when you would need to check for more conditions inside a singleif-thencommand, so you can use nested if statements for this.
Now, let’s discuss some basic conditional arguments that are used in if statements, together with some examples:
- In this example, we will check if the number a user is typing is even or odd. The script will take the input from the user by using the
readcommand; then, it will check if what remains from its division by two is zero or not. This way, it determines if the number is odd or even. We will use theif-then-elsestatement for this example, together with thereadandprintfcommands. The following screenshot shows the code and the execution’s output:
Figure 8.21 – Script to determine an even or odd number
- The following script checks if a filename introduced by the user is indeed a file or not by using the
test -foperator. We will introduce the absolute path of the file we want to run a check on. The script is calledtesting_file.shand its code is shown in the following screenshot:
Figure 8.22 – Checking if a filename that’s been introduced is a file
By running this script, you will be prompted to provide the filename and full path of an existing (or not) file. Let’s do some tests. You will see the output shown in the following figure. We tested if the script is working correctly in three different scenarios: when we do not provide a filename, when we enter a correct filename, and when we enter the wrong filename:

Figure 8.23 – Running the file-checking script
Now that we’ve covered the basics of if conditional statement usage, let’s proceed to other types of statements, such as looping statements.
Using looping statements
Section titled “Using looping statements”In Bash, looping statements use the for, while, and until commands, and we will show you how to use them in this section. Looping statements are used when repeating processes are needed, such as looping through several commands until a condition is met.
Using the for statement
Section titled “Using the for statement”As in any other programming language, the need for iterating appears when repetitive tasks have to be done. This means that some commands need to be repeated until condition(s) are met. This is similar in Bash as in any other programming language, and one of the commands to use is the for command. It has the following structure:
for var in listdo commandsdoneIf you did not have any interaction with such a statement before, we will help you understand what it means. The variables provided through the var parameter are assigned with a series of values provided through the list parameter, in a series of iterations. At the start of the iteration, the variable is set with the current (or starting) value in the list. Each iteration will use another value from the list, until the last item in the list. The number of items in the list will set the number of iterations. For each iteration, the commands inside the commands block will be executed. This is a basic loop we described.
Let’s see some basic uses of the for command. We will loop through a statically declared array. This means that we will not use the input from our user; instead, we will specify the array directly inside the script. We will use a temporary variable (or counter) called i to iterate through the entire length of the array. We use ${array[@]} to specify the array’s length. The loop will stop when the counter (i) reaches this length. The following figure shows the script’s code, the commands used to run it, and the output. Keep in mind that we provided an array that had values already ordered. This is not a sorting algorithm:

Figure 8.24 – Iterating through an array using the for statement
In the following example, we will bring back the discussion on arrays and use some of them inside a for statement. This time, we will show you how to sort an array. We will use most of the structures we’ve already learned about, such as input reading, output formatting, arrays, and for statements.
Important note
Sorting algorithms are outside the scope of this book. We will only use one type of sort (bubble) to show you how to use arrays and for statements and how powerful Bash can be. However, if you plan on doing any serious programming while using the shell, we advise you to use another programming language that is more suited for this type of action, such as Python. Python is incredibly versatile and can successfully be used for many administrative tasks.
Let’s get back to our sorting issue. Let’s say we have a random array that we would like to sort. We will use an array that has integer elements only. To make things more interesting, we will prompt the user to introduce the array elements from the standard input. The following figure shows the code of the script:

Figure 8.25 – Using the bubble sort algorithm to sort an array
Let’s explain the code. We used a variable, n, to specify the length of the array. Then, we used this variable to iterate through all the numbers provided by the user. In the first for statement, we iterate through all the numbers and carefully increase the counter (with the I variable) by each step (the i++ structure). The numbers provided by the user are then stored inside an array called num. When the sorting starts, we use two nested for statements and one if statement. We make use of a new counter called j, which is used to store the value of a new consecutive number inside the array. The if statement compares which of two consecutive numbers inside the array is greater, thus performing the switch between the first two elements inside the array. To perform the switch, we use a temporary counter called k to keep the value of the greater number to make the switch between the two numbers that are being compared. The loop is finished when all the numbers have been cycled through. The final for statement prints the contents of the new, sorted array.
The user input and the output of the command are shown here:

Figure 8.26 – Showing the input and output for our sorting script
In the preceding example, bubble sort is working as follows:
- The first step is to compare the first two elements in the array, which are
45and24, and see which is greater;45is greater than24, so the new array will be24 4556(the algorithm swaps between45and24). - The second step is to compare the next two elements, which are now
45and56(because45was greater than24and is now in the second position; as45is not greater than56, their position will remain unchanged). - The third step is to do one more pass through all the elements and still do the comparison.
Important note
Bubble sort is not an efficient sorting algorithm, but it was a good example of how to use arrays, for and if statements, input from the user, and output formatting. For more information on the bubble sort algorithm or any other type of sorting algorithm, we would advise a thorough online search or that you read the titles we have provided in the Further reading section at the end of this chapter.
Now that you know how to use the for statement, let’s proceed to the while statement.
Using the while statement
Section titled “Using the while statement”The while loop is similar to the for loop, with the difference that it is somehow also a combination of the if statement. So long as a condition is true, the loop is executing the commands. The syntax is as follows:
while conditiondo commandsdoneThe condition is tested every time an iteration is started. If the condition remains true, the exit status is zero, and the commands are executed until the condition changes its status. Let’s see some examples.
In the following script, we’re using a while statement to go through a list of numbers in descending order:

Figure 8.27 – Using a while statement
The while statement will evaluate the [ $max -gt 0 ] condition and iterate until the condition is false. This means that so long as the number you provide is greater than (-gt) zero, the commands will be executed. The commands inside the while loop are simply decreasing the number with every iteration. Otherwise, you will end up in an infinite loop. Thus, the value of the max variable will be lower by one point every time the while loop executes. We tested with two values, once with 10 and again with 30; you can see the output in Figure 8*.27*.
The while statement is very useful and straightforward, being a great addition to the for statement. Now, let’s see the until statement.
Using the until statement
Section titled “Using the until statement”This looping structure is the opposite of while. It uses a condition that is false from the start, and while the condition remains false, the commands inside the structure will be executed. The syntax is as follows:
until conditiondo commandsdoneFor a very quick example, let’s redo the while loop from the previous example by using the until statement this time. Here’s the code:

Figure 8.28 – An example of an until statement
Can you spot the differences between the until and while loops? In the case of until, the iteration continues until the value of the variable is equal to zero, [ $max -eq 0 ]. The commands inside the until loop are the same as the ones used inside the while loop. The condition is different. The output, as you might expect, is the same as when using a while loop.
Before we move on and learn about more advanced programming structures, we’ll provide some basic information about controlling the execution of a loop by using specific keywords.
Exiting loop statements
Section titled “Exiting loop statements”The two commands that are used in Bash to exit loops are break and continue. They are relatively straightforward. Whenever you want to exit a loop, you can use one of them. Let’s use a simple script that iterates through a series of integer numbers until a specified value is reached and it exits the iteration. Here is the code:

Figure 8.29 – Exiting a loop using the break command
When executing, the user is asked to introduce the maximum value for the sequence and the value of break. The for loop goes through the sequence until the value of break is reached, and it exits the loop. We used the break command to exit the loop and started the iteration from zero. You can test the outcome with different values. The following is the output when using a value of 10 for the maximum sequence and a value of 5 for break:

Figure 8.30 – Output of using the break script example
As you can see, the loop exits after 5 is reached. However, it shows the value of 5, it does not skip it. This can be fixed (it is not necessarily an issue, more of an algorithm design decision). Let’s look at the following code:

Figure 8.31 – Breaking loop optimized
For the breaking value to not be shown, we moved the echo $i command after the conditional if-then statement. This will prevent the script from showing the breaking value provided by the user. Both use cases are valid and they provide the same output, so the position of the output printing command is only relevant to your needs.
In the following example, we will show you how to use the continue command to exit a loop. The algorithm is similar to the one used in the break example, except this time, the value provided by the user will not be shown in the output. The break command will exit the loop when a condition is met, whereas the continue command will skip the rest of the command execution that is present after the condition, when a certain condition is met, and will continue to the next iteration of the loop sequence. This difference is sufficient for you to understand the differences between break and continue. Let’s see the code for the same script, using the continue command:

Figure 8.32 – Using the continue command inside a loop
As you can see, the code is similar to what was used in the previous example. The only difference is the use of the continue command instead of break. Now, let’s see the output that’s obtained:

Figure 8.33 – The output when using the continue command
As shown in the preceding figure, the number 5 is not shown, meaning that the loop skipped it when the continue command is used.
You now know quite a bit about scripting in Linux. You know how to use variables, arrays, if and looping statements, and even exiting loops. In the next section, we will show you how to use more advanced programming structures, such as functions.
Working with functions
Section titled “Working with functions”As in most programming languages, functions prove useful when you need to use the same blocks of code multiple times inside a program. By creating functions for specific uses, you can call them anywhere in your script. In Bash, there are two ways to create a function. First, you can use the function keyword, followed by the function’s name, as shown in the following syntax:
function name { commands}Alternatively, you can use parentheses after the function’s name, as shown in the following syntax:
name() { commands}The name from the syntax is a unique name that the function will use throughout the script. The commands are represented by one or more shell commands that are executed by the function in their order of appearance. Simplified, you can look at functions as scripts inside scripts. Let’s see some examples.
With the risk of being redundant, we will use one of the scripts we already created and use it as a function, just to show you how functions work, for starters. We will use the script that sorts numbers in descending order and make it a function. But before that, let’s give you a word of caution regarding functions.
Important note
Functions must be created before they are called. Calling a function is the process of running it inside a script. If you create the function after you call it, the script will give you an error because Bash is a single-pass interpreter. A good practice is to create the functions at the beginning of a script. This way, they will be available whenever they’re needed throughout the script.
So, here it is – our first function is shown in the following screenshot. As you can see, first, we created the sorting function, and then we called it:

Figure 8.34 – Running our first function
At this point, you know how to create and call a function inside a shell script, but there is much more to this matter than just that. We will try and give you all the necessary information about functions so that you will be able to use them in your scripts, but if you want to learn more, please consider the titles provided in the Further reading section.
In the next section, we will walk you through different function capabilities, such as output, variables, and array handling.
Advanced function capabilities
Section titled “Advanced function capabilities”Every function inside the Bash shell, as stated before, works like a script by itself. This means that it can manage variables, arrays, and output in the same way as a script. In this section, we will show you how to use variables, arrays, and output inside functions.
Using variables inside functions
Section titled “Using variables inside functions”Both types of variables (global and local) can be used inside functions. Let’s provide an overview of the differences between these two types of variables. The global ones are visible and available throughout the system, while the local ones are only available inside the function where they were declared. By default, all variables in Bash are defined as global variables, including the ones defined inside functions. To declare local variables inside functions, we can use the local keyword. Let’s see a basic example to understand how this works:

Figure 8.35 – Showing how local and global variables work in functions
The preceding figure shows how the variables were declared. For example, first, we declared the var1='1' and var2='2' variables. By default, they are set as global variables. Then, inside the var_function function, we modified the values of the two variables, but for one of them, we used the local keyword to define it local to the function. For the other one, we did not use the same keyword – we defined it as we did before the function. Thus, when printing the variables to the standard output after the function is run, only var2 will keep the value given to it inside the variable, compared to var1, which was declared locally and had a different value only inside the function.
Using arrays inside functions
Section titled “Using arrays inside functions”Unlike variables, arrays inside functions are somewhat problematic. There are two scenarios to consider: one when you need to pass arrays from the script to the function, and one when you would need to pass an array from the function back to the script. In the first case, you can’t use the array as a function parameter because only the first value of the array will be used by the function. Thus, the convenient way is to break the array and then rebuild it inside the function, even though it sounds and proves unpractical. In the second case, the practice of handling arrays is similar to the first scenario as the function will output the values in the correct order and the script will reassemble the value into an array. Let’s see an example:

Figure 8.36 – Using arrays inside functions
In the preceding example, we used two functions, one for each of the scenarios described at the beginning of this subsection. The test_function_1 function inside the script shows the way we can pass array elements to the function. The test_function_2 function shows how arrays are being returned from functions. Here’s the output:

Figure 8.37 – Output of using arrays in functions
At this point, you’ve learned how to create scripts and how to use arrays, variables, programming structures, and functions. Now, it’s time to learn how to use sed and (g) awk both at the command line and in scripts.
Using sed and (g)awk commands
Section titled “Using sed and (g)awk commands”Both sed and (g) awk are advanced tools that are used for manipulating text files. sed is a stream editor and awk is a programming language. We also use the gawk reference (thus the letter g used inside parentheses) as it is the GNU implementation of awk, offering more features and extensions. Let’s learn how to use both of them at the command line.
Using sed at the command line
Section titled “Using sed at the command line”sed is more than a simple command. It is a data stream editor that edits files based on a strict set of rules supplied beforehand. Based on these rules, the command reads the file line by line and the data inside the file is then manipulated. sed is a non-interactive stream editor that makes changes based on a script, and in this respect, it is well suited for editing more files at once or for doing mundane repetitive tasks. The sed command’s general syntax is as follows:
sed OPTIONS… [SCRIPT] [FILE…]The sed command uses different script subcommands, and one of the common subcommands that’s used is for text substitution. There are many other use cases that we will not discuss here, but if you feel the need to learn more about the sed tool, there are plenty of great materials online and in print. For example, the following link could be useful: https://www.ibm.com/docs/en/aix/7.2?topic=s-sed-command.
The common syntax that’s used for text substitution is as follows:
sed 's/regex/replacement/flag'Here are some examples of the most common use cases of sed:
- Replace one name with another inside a text file. For this example, we will use a new file called
poemin our home directory. Inside it, we generated a random poem. The task is to replace the nameJanewithElanefrom within the file. The letterg, as a flag of the command, specifies that the operation should be global – that is, it should be applied to the entire text document. Here is the result:
Figure 8.38 – Using the sed command to replace a string in a text file
If you check the original file using the cat command, you will see that sed only delivered the changed name result to the standard output and did not make any changes to the original file. To make the changes to the file permanent, you will have to use the - i attribute.
- In the following example, we’re adding new spaces at the beginning of each line and redirecting the output to a new file. We’re using the same
poemfile as before. The beginning of a file is represented by the^character:
Figure 8.39 – Using sed to add spaces
- We will use
sedto show only the second line from thepoemfile and to show all the lines except for line 2:
Figure 8.40 – Using sed to show specific lines in a file
- Let’s show only lines 4 to 6 from a file – in our case, the
/etc/passwdfile:
Figure 8.41 – Using sed to show a specific number of lines in a text file
- Here is a more practical exercise. We will show the contents of
/etc/apt/sources.listfrom Ubuntu without the commented lines. To do this, use theThis command deletes the lines inside the file that start with the hashtag (sed '/^#/g' /etc/apt/sources.list#) character, represented by the^#characters inside the command. Those are the comments inside the file. We also use thegflag to specify that the operation is global for that file. The following is part of the output provided by the command. Use it on your Ubuntu system and analyze your output as well:
Figure 8.42 – Use of sed to show only lines with no comments
In the following subsection, we will explore the awk command at the command line.
Using awk from the command line
Section titled “Using awk from the command line”awk is much more than a simple command – it is a pattern-matching language. It is a full-fledged programming language that was the base for PERL. It is used for data extraction from text files, with a syntax similar to C. It sees a file as being composed of fields and records. The general structure of the awk command is as follows:
awk '/search pattern 1/ {actions} /search pattern 2/ {actions}' fileThe true power of awk is beyond the scope of this chapter, so we will show no more than one simple example of its use that could prove practical for a future system administrator.
As an example, we will generate a list containing the names of all the packages installed by Ubuntu. We only want to print the name of each package, not all the other details. For this, we will use the following command:
sudo dpkg -l | awk '{print $2}' > package-listThis command is only showing the names of the packages that have been installed. Here is the output:

Figure 8.43 – Using awk to generate a list of package names
Generally, to see the installed packages in Ubuntu, we would run the dpkg -l command. In the preceding example, we piped the output of that command to the awk command, which printed the second column (field) from the dpkg -l output ('{print $2}'). Then, we redirected everything to a new file called package-list and used the tail command to see the last 10 lines of the newly created file.
Both sed and awk are very powerful tools, and we have merely scratched the surface of what they can do. Please feel free to dig deeper into these two awesome tools.
Using scripts to showcase interprocess communication
Section titled “Using scripts to showcase interprocess communication”Interprocess communication (IPC) was introduced in Chapter 5. In this chapter, we will revisit the mechanism that can make use of scripts. To illustrate most of these communication mechanisms, we will build our examples using a model of producer and consumer processes. The producer and consumer share a common interface, where the producer writes some data that’s read by the consumer. IPC mechanisms are usually implemented in distributed systems, built around more or less complex applications. Our examples will use simple Bash scripts (producer.sh and consumer.sh), thus mimicking the producer and consumer processes. We hope that the use of such simple models will still provide a reasonable analogy for real-world applications.
Now, let’s look at shared storage, named and unnamed pipes, and sockets IPC mechanisms, all of which we introduced in Chapter 5 but did not cover in detail.
Shared storage
Section titled “Shared storage”In its simplest form, the shared storage of an IPC mechanism can be a simple file that’s been saved to disk. The producer then writes to a file while the consumer reads from the same file. The producer and consumer data feeds are identical at any time. The two processes communicate via the shared storage file.
In this simple use case, the obvious challenge is the integrity of the read/write operations due to possible race conditions between the underlying operations. To avoid race conditions, the file must be locked during write operations to prevent overlapping I/O with another read or write action. To keep things simple, we’re not going to resolve this problem in our naive examples, but we thought it’s worth calling it out.
In our example, the producer writes a new set of data (10 random UUID strings) every 5 seconds to the storage file. The following screenshot shows the producer’s script:

Figure 8.44 – The producer script (using shared storage)
The consumer reads the content of the storage file every second. The following screenshot shows the consumer’s script:

Figure 8.45 – The consumer script (using shared storage)
When running both scripts, the producer creates random strings and writes them to the storage file, and the consumer reads the producer’s output from the same file. The output is shown in the following screenshot:

Figure 8.46 – The producer (left) and consumer (right) communicating through shared storage
Next, we will show you how unnamed pipes work.
Unnamed pipes
Section titled “Unnamed pipes”Unnamed or anonymous pipes, also known as regular pipes, feed the output of a process to the input of another one. Using our producer-consumer model, the simplest way to illustrate an unnamed pipe as an IPC mechanism between the two processes would be to do the following:
producer.sh | consumer.shThe key element of the preceding illustration is the pipe (|) symbol. The left-hand side of the pipe produces an output that’s fed directly to the right-hand side of the pipe for consumption. To accommodate the anonymous pipe IPC layer, we’ll make two new scripts called producer2.sh and consumer2.sh. The code is shown in the following screenshot:

Figure 8.47 – The producer2 (left) and consumer2 (right) scripts (using an unnamed pipe)
In our modified implementation, producer2.sh prints some data to the console (10 random UUID strings). consumer2.sh reads and displays either the data coming through the /dev/stdin pipe or the input arguments if the pipe is empty. Line 6 in the consumer2.sh script checks the presence of piped data in /dev/stdin (0 for fd0):
if [ -t 0 ]The output of the producer-consumer communication is shown in the following screenshot:

Figure 8.48 – The producer feeding data into a consumer through an unnamed pipe
The output clearly shows the data being printed out by the consumer process. (Note the "Consumer data:" header preceding the UUID strings.)
One of the problems with IPC anonymous pipes is that the data that’s fed between the producer and consumer is not persisted through any kind of storage layer. If the producer or consumer processes are terminated, the pipe is gone, and the underlying data is lost. Named pipes solve this problem, as we will show you in the next section.
Named pipes
Section titled “Named pipes”Named pipes, also known as First In, First Outs (FIFOs), are similar to traditional (unnamed) pipes but substantially different in terms of their semantics. An unnamed pipe only persists for as long as the related process is running. However, a named pipe has backing storage and will last so long as the system is up, regardless of the running status of the processes attached to the related IPC channel.
Typically, a named pipe acts as a file, and it can be deleted when it’s no longer being used. Let’s modify our producer and consumer scripts so that we can use a named pipe as their IPC channel:

Figure 8.49 – The producer3 (left) and consumer3 (right) scripts (using named pipe)
The named pipe is pipe.fifo (line 3 in both scripts). The pipe file is created (if it’s not already present) by either the producer or consumer when they start (line 6). The related command is mkfifo (see man mkfifo for more information).
The producer writes a random UUID to the named pipe every second (line 14 in producer3.sh), where the consumer immediately reads it (lines 10 to 12 in consumer3.sh):

Figure 8.50 – producer3 (left) and consumer3 (right) communicating through a named pipe
We started both scripts – the producer and the consumer – in an arbitrary order. After a while, we stopped (interrupted) the consumer (step 1). The producer continued to run but automatically stopped sending data to the pipe. Then, we started the consumer again. The producer immediately resumed sending data to the pipe. After a while, we stopped the producer (step 2). This time, the consumer became idle. After starting the producer again, both resumed normal operation, and data began flowing through the named pipe. This workflow has shown the persistence and resilience of the named pipe, regardless of the running status of the producer or consumer processes.
Named pipes are essentially queues, where data is queued and dequeued on a first-come-first-served basis. When more than two processes communicate on the IPC named pipe channel, the FIFO approach may not fit the bill, especially when specific processes demand a higher priority for data processing. Next, we will show you how sockets work.
Sockets
Section titled “Sockets”There are two types of IPC socket-based facilities:
- IPC sockets: Also known as Unix domain sockets
- Network sockets: Transport Control Protocol (TCP) and User Datagram Protocol (UDP) sockets
IPC sockets use a local file as a socket address and enable bidirectional communication between processes on the same host. On the other hand, network sockets extend the IPC data connectivity layer beyond the local machine via TCP/UDP networking. Apart from the obvious implementation differences, the IPC socket’s and network socket’s data communication channels behave the same.
Both sockets are configured as streams, support bidirectional communication, and emulate a client/server pattern. The socket’s communication channel is active until it’s closed on either end, thereby breaking the IPC connection.
Let’s adapt our producer-consumer model to simulate an IPC socket (Unix domain socket) data connectivity layer. We’ll use netcat to handle the underlying client/server IPC socket’s connectivity. netcat is a powerful networking tool for reading and writing data using TCP, UDP, and ICP socket connections. If netcat is not installed by default on your Linux distribution of choice, you may look to install it as follows.
On Ubuntu/Debian, use the following command:
sudo apt install netcatOn Fedora/RHEL, use the following command:
sudo dnf install nmapFor more information about netcat, please refer to the related system reference manual (man netcat).
In the following example, we will use a producer4.sh file and a consumer4.sh file. The code for each file is shown in the following screenshot:

Figure 8.51 – The producer4 (left) and consumer4 (right) scripts (using IPC sockets)
The producer acts as the server by initiating a netcat listener endpoint using an IPC socket (the last line in producer4.sh):
nc -lU "${SOCKET}"The -l option indicates the listener (server) mode, while the -U "${SOCKET}" option parameter specifies the IPC socket type (Unix domain socket). The consumer connects to the netcat server endpoint as a client with a similar command (the last line in consumer4.sh). The producer and consumer both use the same (shared) IPC socket file descriptor (/var/tmp/ipc.sock) for communication.
The producer sends random UUID strings every second to the consumer (the while - do - done structure in producer4.sh). The related output is captured in stdout with the tee command before being piped to netcat:

Figure 8.52 – producer4 (left) and consumer4 (right) communicating through an IPC socket
The consumer gets all the messages (UUIDs) that have been generated by the producer. To show you that the consumer listens, we first started the consumer script, which generated two errors, so long as the producer was not sending data through the socket. Once we started the producer script, the consumer started to receive data. When we interrupted the producer, the consumer stopped immediately.
In our producer-consumer model, we used netcat for the IPC socket communication layer. Alternatively, we could use socat, a similar networking tool. In the next section, we will show you a quick example of using a script for a specific Linux administrative task. As a bonus, we will also show you how to build applications from source.
Scripting for administrative tasks
Section titled “Scripting for administrative tasks”Scripting in a Linux operating system is mainly useful when it can help with mundane administrative tasks. This way, you can automate your workflow in ways that will make your job easier and more enjoyable. There are many use cases of shell scripts, and we will only provide you with a quick and easy example, hoping that it will suffice for understanding how a script can be used for a sysadmin task.
In the following sections, we will show you how to build a distribution-specific package from a source. This is something that should have been presented to you in Chapter 4, but at that time, you did not know how to create a script. In this chapter, we only used Ubuntu 22.04.2 LTS for our examples. In the following sections, we will use Fedora 37 Server Edition for our examples.
Creating scripts for system administrative tasks
Section titled “Creating scripts for system administrative tasks”In this section, we will show you a couple of scripts for administrative tasks. As we stated at the beginning of this chapter, a shell script is a sequence of Bash commands that are executed when the file is running. In the following subsections, we will create two scripts that will do two different administrative tasks.
An updating script example
Section titled “An updating script example”This script will use the dnf update command to update the system at a specified time. It is a very basic script that runs just a simple command and shows some messages to standard output. Remember that we will be using a Fedora Server distribution this time. The simplest way would be to run the following command inside the script:
sudo dnf update -yThe issue is that it requires the sudo password. This defies the purpose of automation because the user must provide the password manually. Let’s learn how to overcome this issue. First, let’s see the code of the script:

Figure 8.53 – A simple update script
Now, if you want the command to be run without the sudo password, you will have to edit the /etc/sudoers file and modify/add some things.
Important note
Please take into consideration that this method will have system-wide effects, not only on the script you want to run. It is not considered a safe measure and we advise you to use it with extreme care and consideration on any production system.
Remove the comment before %wheel in the following line:
%wheel ALL=(ALL) NOPASSWD: ALLThis will provide a password-less action for every user that is in the wheel group. This should include the user you are using. If it wasn’t inside the wheel group, you wouldn’t be able to use sudo with it. In our case, the packt user is inside the wheel group. To test if it works, you can run the script as a regular user and see if the prompt for the sudo password will appear.
Now, we will have to schedule the script to run at a certain time. Don’t forget to make your script file executable to be able to run it. As we are using a server distribution, we assume that this machine is running 24/7 without interruptions, so running at startup would make no sense. Furthermore, we want to ensure that the system is always up to date. To schedule the script, we will use cron and crontab. We will show you how they work in the next section.
Scheduling scripts in Linux with cron
Section titled “Scheduling scripts in Linux with cron”Using crontab might look scary at first, but once you get to know it, you will find it very useful. Perhaps the most intimidating aspect of using cron jobs is the definition process, especially the schedule setup. However, a very useful example of how to set the cron date is provided inside the / etc/crontab file:

Figure 8.54 – Example of a cron job definition in /etc/crontab
We believe that the preceding screenshot is self-explanatory. Now, let’s set up a new cron job for our updating script. We will use the crontab -e command. This command will use the default shell text editor, which in our case (in Fedora) is Vim. Running the crontab -e command will start a new Vim instance where the job should be written. Here is our code:
00 23 * * 0 packt /home/packt/update_script.shLet’s explain this. In the preceding example, we set the new update script file to run at 23:00 every Sunday. The user that is running it is packt.
Once the line of code is created, you can check if the cron job was created by using the crontab -l command. If you want to see the cron jobs of certain users, you can use the following command:
sudo crontab -u packt -lHere, packt is our user. The following snippet shows the code, which can be enhanced inside crontab with an output and error message redirection to /dev/null. This could be useful when we don’t want to see the command’s output or if any errors occur and we don’t need to see them. The line would be modified as follows:
00 23 * * 0 packt /home/packt/update_script.sh > /dev/null 2>&1crontab is a powerful tool that will prove of great help whenever you need to schedule tasks in Linux. However, it is not the only tool available for the job. Feel free to explore other tools available, such as the at command. Next, we will go through another short script for backing up files.
A backup script example
Section titled “A backup script example”Another common use for scripting is for backing up files. We will create a new script for this task and we will schedule it according to our needs. The script’s code is shown in the following screenshot:

Figure 8.55 – A short backup script
The code is backing up the /home/packt directory to the /mnt/backup directory. The contents of /home/packt will be archived using the tar command and saved as .tgz files using the current date and hostname for the filename.
Important note
Using the date format can be daunting and intimidating at first, but knowing how to use it in your scripts will prove invaluable. Use the date --help command for more information.
In the next subsection, we will show you how to create a small random password generator in Bash.
A random password generator script
Section titled “A random password generator script”Keeping your online or local accounts secure is extremely important, so secure passwords should be used as a general rule. We will provide you with an example of a script that generates random passwords.
There are many password generators available to use in Linux, but we thought that it would be fun if you created such a small script by yourself. One default password-generating app available in Bash is pwmake, for example. However, we will create our own password-generating script. We will use openssl and an encoding mechanism called base64. For more information, go to https://developer.mozilla.org/en-US/docs/Glossary/Base64. Keep in mind that there are many other ways to generate random characters in Linux, one highly used being the /dev/urandom pseudo-random number generator. Feel free to explore as many ways as you like. In the meantime, here is our code for the password-generating script:

Figure 8.56 – Password-generating script
When running the script, you will be prompted to provide the number of characters you want to use and the number of passwords to be generated:

Figure 8.57 – The output of running the password-generating script
Scripting is an invaluable task you should master. We barely scratched the surface of shell scripting, but the information in this chapter should give you a good start so that you can start developing sysadmin scripts.
In the next subsection, we will show you how to package your scripts into full-fledged apps that can be installed on the Linux command line. This is an addition to Chapter 3, where you learned about Linux package management.
Packaging scripts
Section titled “Packaging scripts”Bash scripts are pieces of software like any other, so they can be deployed with Linux distributions as platform-specific packages. Just like you would package any other piece of software code, you can package a piece of shell scripting code. In this section, as an add-on to the knowledge you gathered in Chapter 3, we will show you how to package a Bash script. As stated before, the information provided here can easily be used for other software sources (usually, in Linux, there is C/C++, Python, Rust, Java, or Go). In the next subsection, we will show you how to create an RPM package for RHEL-based distributions. We will use Fedora Linux 37 in our example.
Creating RPM packages from source
Section titled “Creating RPM packages from source”To create an RPM package, we will use the password generator script we developed in the previous section. Before going into more details, we’ll provide a short word on programming language types and where Bash fits in.
Important note
Usually, software programs are developed using human-readable source code. This code needs to be translated into machine code so that the computer will understand it. There are several large generic types of programming languages: interpreted (such as Python or Bash – which is a CLI language but still considered an interpreted language) and compiled (such as C/C++, Java, and Go) are the widely known ones. The Bash source code is executed line by line, without prior compilation into specific machine code. For more information, check out https://en.wikipedia.org/wiki/List_of_programming_languages_by_type.
Often, the software source code is distributed in the form of compressed archives (.tar.gz files or tarballs) that are then packaged into RPM packages. The archive usually consists of the source code file and a license file. This license file offers information about the type of license the software is distributed with. In the case of free and open source software (FOSS), the license is usually GPLv3 or GLPLv3, but other types such as the MIT license or Apache and BSD licenses are also used.
Important note
For detailed information on FOSS license types, check out https://en.wikipedia.org/wiki/Comparison_of_free_and_open-source_software_licenses.
The following are the necessary steps for creating an RPM package from a Bash script:
- Create a directory: First, we will create a new directory where all the specific files will be stored. The directory will be named
passgen-0.1. - Create a license file: For our Bash script, we will create a license file to use with the package. The file will be named
LICENSE.txtand placed inside the newly created directory. We will use the GPLv3 open source license. The text to be added to your file can be found under the How to Apply These Terms to Your New Programs section at https://www.gnu.org/licenses. - Move the Bash script inside the directory: We will also copy the
passgen_script.shfile inside the new directory and change its name topassgen-0.1.sh. - Add the script to the system: We will add the
passgen-0.1.shscript to the Filesystem Hierarchy Standard$PATHusing theinstallcommand. We use theinstallcommand because our simple Bash script does not need any dependencies:This will ensure that we can run thesudo install -m 0755 passgen-0.1.sh /usr/bin/passgenpassgenscript without using the full path. - Create the tarball: Once both the source code and the license files are ready, we will create a
tar.gzarchive with thetar -cvzf passgen-0.1.tar.gz passgen-0.1.sh LICENSE.txt - Install specific RPM packaging utilities: To create RPM packages, we need some specific utilities, such as the
rpmdevtoolspackage. We can install it using theThis will install all additional packages and dependencies to set up the packaging workspace.sudo dnf install rpmdevtools - Set up the workspace: To set up the workspace, we will run the
This will create a newrpmdev-setuptree
rpmbuilddirectory and sub-directories inside your home directory. The newrpmbuilddirectory has the following structure:
Figure 8.58 – The rpmbuild’s directory structure
The BUILD directory contains information about the build process; the RPMS directory contains binary RPMs; the SOURCES directory contains the tarball of the compressed source code; the SPECS directory contains the SPEC file; and the SRPMS directory contains source RPMs.
- Add the tarball to the ~/rpmbuild/SOURCES directory: We will add the compressed file we created earlier to the
~/rpmbuild/SOURCESdirectory with the following command (from within thepassgen-0.1directory):Now, the source file tarball is in the right place.cp passgen-0.1.tar.gz ~/rpmbuild/SOURCES/ - Configure a new SPEC file: First, we will create a new
SPECfile by running therpmdev-newspeccommand from inside the~/rpmbuild/SPECSdirectory:You can list the contents of therpmdev-newspec passgen~/rpmbuild/SPECS/directory, after which you will see that a new file calledpassgen.specwas created. The newSPECfile contains automatically generated lines with specific RPM macros defined. We will not get into much detail about macros, but you can find more information at https://rpm-software-management.github.io/rpm/manual/macros.html. As Bash is an interpreted language, some default specifications from theSPECfile are not needed, such asBuildRequires, which was deleted. For the%buildsection, we did not provide any information as Bash does not need anything specific. TheSPECfile is shown in the following screenshot:
Figure 8.59 – The SPEC file’s entries
- Build the RPM package: The RPMs are built based on the specifications inside the
SPECfile, but there are other use cases, such as building an RPM from a source RPM (SRPM), for example. We will show you how to build a binary RPM from sources. In all of the cases outlined, the command to use isrpmbuild, but the options are different. When building source RPMs, we will use the-bsoption, when rebuilding RPMs from source, we will use the--rebuildoption, and when building binary RPMs from source, we will use the-bboption. In our case, we will create a binary from source and use the following command:The build was successful and we can verify if the newrpmbuild -bb ~/rpmbuild/SPECS/passgen.spec.rpmfile was created. We can check this at~/rpmbuild/RPMS/, where we will have a new directory based on the CPU architecture. In our case, we will have a newnoarchdirectory that contains the.rpmfile for our password generator. The following is the output:
Figure 8.60 – The new RPM binary package
Here you are, building your very first RPM binary package from a Bash script file! You can do this for any type of source file you might develop. Building binary packages is not a very difficult task, and with good documentation about the specifics of macros used in the SPEC file, you are good to go. More information about the available documentation on this matter can be found in the Further reading section.
Summary
Section titled “Summary”In this chapter, you learned how to create Bash scripts in Linux. You now know about shell variables and script variables, as well as how to use programming structures such as loops, conditionals, and arrays inside scripts. You now further understand how interprocess communication works. The skills you have learned will help you create scripts in any Linux distribution. When you are creating scripts, you will put your text editor knowledge into action too. You will use the skills that you’ve learned regarding Bash scripting in many aspects of your everyday job as a system administrator too.
In the next chapter, you will learn how to manage security in Linux, the access control mechanisms, AppArmor and SELinux, and firewalls. This skill is important for any administrator and must be part of any advanced training.
Questions
Section titled “Questions”In this chapter, we covered Linux Bash scripting. Here are some questions for you to test your knowledge and for further practice:
- What are arrays and how are they used in Bash scripts? Can there be hybrid types? Hint: Think of their types, how they are defined, and how they are used.
- What is an infinite loop? Hint: This is something you would not like to use but should know how to escape if needed.
- How many types of loops can be used in a Bash script? Hint: Not that many, but more than conditional loops.
- Find out how to build a DEB binary package. Hint: Use the examples from Debian, which can be found at https://www.debian.org/doc/manuals/maint-guide/build.en.html and https://wiki.debian.org/HowToPackageForDebian.
Further reading
Section titled “Further reading”For more information about what was covered in this chapter, please refer to the following resources:
- Linux Administration Best Practices, by Scott Alan Miller, published by Packt
- Linux Command Line and Shell Scripting Techniques, by Vedran Dakic and Jasmin Redzepagic, published by Packt
- Official documentation from https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/packaging_and_distributing_software/index, https://docs.fedoraproject.org/en-US/packaging-guidelines/RPMMacros/ (RPM macros), and rpm.org