Basic Shell Script Construction
local graph
Chapter 8 — Basic Shell Script Construction
Section titled “Chapter 8 — Basic Shell Script Construction”Yeah, I know. You’re dying to start creating some shell scripts, but haven’t been able to do that yet. So, in this chapter, we’ll look at the basics of shell script construction. We’ll then wrap things up by looking at some shell scripts that are both practical and useful.
Many of the techniques that I’m presenting in this chapter work for any shell, but I’ll also present some that might only work on bash. So, just to keep things simple though, I’ll be sticking with bash for now. In Chapter 22, Using the zsh Shell, I’ll show you techniques that are specific to zsh. In Chapter 19, Shell Script Portability, I’ll show you techniques that will work on a wide variety of shells.
The topics that you’ll see in this chapter include:
- Understanding basic shell script construction
- Performing tests
- Understanding subshells
- Understanding scripting variables
- Understanding array variables
- Understanding variable expansion
- Understanding command substitution
- Understanding decisions and loops
- Understanding positional parameters
- Understanding exit codes
- More information about echo
- Looking at some real-world examples
All right, if you’re ready, let’s jump in.
Technical Requirements
Use any Linux distro that has bash installed. If you’re a Mac user, you’ll want to use one of your Linux virtual machines, because some of the scripts use commands that won’t work on macOS. Feel free to follow along on your local machine as you go through this chapter, but also be aware that I will provide some actual hands-on labs.
I’ve also included one hands-on exercise that uses a FreeBSD virtual machine. Create the FreeBSD virtual machine and install both sudo and bash, as I showed you in the book’s Preface.
Also, as I explained in the Preface, you can download the scripts from the Github repository by doing:
git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.gitUnderstanding Basic Shell Script Construction
The first thing you’ll need to do when creating a shell script is to define which shell you want to use to interpret the script.
You might have a particular reason for choosing one shell over another. That’s something we’ll talk about in Chapter 19, Shell Script Portability, and Chapter 22, Using the Z Shell.
You’ll define the shell to use as the interpreter in the shebang line, which is the first line of the script. It will look something like this:
#!/bin/bashNormally of course, a line that begins with the # sign would indicate a comment that would be ignored by the shell. The shebang line—and please don’t ask me why it’s called that—is an exception to that rule. In addition to defining a specific shell that you want to use, such as /bin/bash or /bin/zsh, you can also define the generic /bin/sh shell to make your scripts more portable, so that they’ll run on a wider variety of shells and operating systems. Here’s how that looks:
#!/bin/shThis generic sh shell is supposed to make it so that you can run your scripts on different systems that might or might not have bash installed. But, it’s also problematic because the various shells that sh represents aren’t fully compatible with each other. Here’s the breakdown of how it works:
- On FreeBSD and possibly other Berkeley Software Distribution (BSD)-type systems, the sh executable is the old-school Bourne shell, which is the ancestor of the Bourne Again Shell (bash).
- On Red Hat-type systems, sh is a symbolic link that points to the bash executable. Be aware that bash can use certain programming features that the other shells in this list can’t use. (I’ll explain more about this in Chapter 19, Shell Script Portability.)
• On Debian/Ubuntu-type systems, sh is a symbolic link that points to the dash executable. dash stands for Debian Almquist Shell, which is a faster, more lightweight implementation of bash.
• On Alpine Linux, sh is a symbolic link that points to ash, which is a lightweight shell that’s part of the busybox executable. (On Alpine, bash is not installed by default.)
• On OpenIndiana, which is a Free Open Source Software fork of Oracle’s Solaris operating system, sh is a symbolic link that points to the ksh93 shell. This shell, which is also known as the Korn shell, is somewhat, but not completely, compatible with bash. (It was created by a guy named David Korn, and has nothing to do with any vegetable.)
• On macOS, sh is a symbolic link that points to bash. (Curiously, zsh is the default login shell on macOS, but bash is still installed by default and is available for use.)
Be aware that using #!/bin/sh in your scripts can be problematic. That’s because the various shells on the various operating systems that #!/bin/sh represents aren’t fully compatible with each other. So, let’s say that you’re creating a script on a Red Hat machine, on which sh points to bash. There’s a real possibility that the script won’t run on either a Debian or a FreeBSD machine, on which sh points to dash and Bourne shell, respectively. For that reason, we’ll concentrate on bash for now, and will just use #!/bin/bash as our shebang line. And, as I mentioned before, we’ll talk more about this topic in Chapter 19, Shell Script Portability.
A shell script can be as simple or as complex as your needs dictate. It can be just one or more normal Linux/Unix commands put together in a list, to be performed sequentially. Or, you can have scripts that can approach the complexity of programs written in a higher-level programming language, such as C.
Let’s start by taking a look at a very simple, one-command script.
#!/bin/bashThis is a simple one-line script that I used to use to back up my images directory on one computer to a backup directory on a Debian computer. It uses rsync, with its appropriate options, to synchronize the two directories via a Secure Shell (ssh) session. (Although I normally don’t like to allow the root user to do ssh logins, in this case it’s necessary. Obviously, I would only do this on a local network, and would never do it across the Internet.) Appropriately, I named the script rsync_with_debian. Before I could run the script, I had to add the executable permission, like this:
chmod u+x rsync_with_debianOn the second line of this rsync_with_debian script, right after the shebang line, you see the exact same command that I would have typed on the command-line if I didn’t have the script. So, you see, I’ve greatly simplified things by creating a script.
To make this script available to all users on the system, place it in the /usr/local/bin/ directory, which should be in everyone’s PATH setting.
Before going further, let’s reinforce what you’ve just learned with a hands-on lab.
Hands-on Lab — Counting Logged-in Users
This lab will help you create a shell script that shows how many users are logged in, and then modify it so that only unique users are listed. (This script uses some of the text stream filters that you learned about in the previous two chapters.)
-
On one of your Linux virtual machines, create three additional user accounts. On your Fedora virtual machine, do it like this, except choose your own user names:
sudo useradd vickysudo passwd vickyOn a Debian virtual machine, do it like this:
sudo adduser vicky -
At the local terminal of the virtual machine, obtain its IP address, like this:
ip a -
Open four terminal windows on your host machine. Using the IP address of your own virtual machine, log into your own account from one window, and then log into each of the other accounts from the other windows. The commands will look something like this:
-
From the terminal window where you’re logged in, view all of the users who are currently logged in, like this:
whoYou should see five users, because your own account will show up once for the local terminal log-in, and once for the remote ssh log-in.
-
Create the logged-in.sh script, and make it look like this:
#!/bin/bashusers="$(who | wc -l)"echo "There are currently $users users logged in."I’m using the concept of command substitution to assign the output of the who | wc -l command to the value of the users scripting variable. (I’ll tell you more about command substitution later, so don’t stress out about it just yet.)
-
Make the script executable, like this:
chmod u+x logged-in.sh
- Now, run the script, like this:
./logged-in.shThe output should look like this:
There are currently 5 users logged in.The problem here is that there are really only four users, because your own username is counted twice. So, let’s fix that.
- Modify the logged-in.sh script so that it now looks like this:
#!/bin/bashusers="$(who | wc -l)"echo "There are currently $users users logged in."echouniquusers="$(who | cut -d " " -f1 | sort | uniq | wc -l)"echo "There are currently $uniquusers unique users logged in."The variable uniquusers is created by all of the commands that are piped to each other inside the (). The cut operation is delimited by a blank space (-d ” ”) and the first field (-f1) is what you will cut from the output of who. That output is piped to sort and then to uniq, which will only send the names of unique users to the wc -l command.
- Run the script again, and the output should look like this:
There are currently 5 users logged in.There are currently 4 unique users logged in.- Make one last modification to the script to list the names of the unique users who are logged in. The completed script will look like this:
#!/bin/bashusers="$(who | wc -l)"echo "There are currently $users users logged in."echouniquusers="$(who | cut -d " " -f1 | sort | uniq | wc -l)"echo "There are currently $uniquusers unique users logged in."echolistusers="$(who | cut -d " " -f1 | sort | uniq)"echo "These users are currently logged in: \n$listusers "- Run the script again, and you should get output that looks something like this:
There are currently 5 users logged in.There are currently 4 unique users logged in.These users are currently logged in:<!-- page: 193 (printed 1) -->cleopatradonniefrankvickyCongratulations! You’ve just created your first shell script. Now, let’s do some testing.
Performing Tests
There will be times when your scripts will need to test for a certain condition before making a decision on which action to take. You might need to check for the existence of a certain file or directory, whether certain permissions are set on a file or directory, or for a myriad of other things. There are three ways to perform a test, which are:
- Use the keyword test followed by a test condition, with another command joined to it with either a && or a || construct.
- Enclose the test condition within a set of square brackets.
- Use an if .. then construct
Let’s start by looking at the test keyword.
Using the test Keyword
For our first example, let’s test to see whether a certain directory exists, and then create it if it doesn’t. Here’s how that works:
[donnie@fedora ~]$ test -d graphics || mkdir graphics[donnie@fedora ~]$ ls -ld graphics/drwxr-xr-x. 1 donnie donnie 0 Sep 26 15:41 graphics/[donnie@fedora ~]$Now, let’s put that into the test_graphics.sh script:
#!/bin/bashcdpwdtest -d graphics || mkdir graphicscd graphicspwdLet’s run this script to see what we get:
[donnie@fedora ~]$ ./test_graphics.sh/home/donnie/home/donnie/graphics[donnie@fedora ~]$As you may have guessed, the -d operator stands for directory. The || construct causes the mkdir command to run if the graphics directory doesn’t exist. And of course, if the directory already exists, it won’t get created again. This is a good safety measure that can prevent you from accidentally overwriting any existing files or directories. (I’ll show you a chart with more test operators in just a moment.)
Now, let’s look at the second way to perform a test.
Enclosing a test Condition Within Square Brackets
The second way to perform a test is to enclose the test condition within a pair of square brackets, like so:
[ -d graphics ]First, note how you must have a blank space after the first bracket and before the second one. This tests for the existence of the graphics directory, just as the test -d construct did. Now, let’s put that into the test_graphics_2.sh script, like so:
#!/bin/bashcdpwd[ -d graphics ] || mkdir graphicscd graphicspwdRunning this script will give you the exact same output as the first script. Now, let’s put a twist on things. Modify the test_graphics_2.sh script so that it looks like this:
#!/bin/bashcdpwd[ ! -d graphics ] && mkdir graphicscd graphicspwdThe ! is a negation operator, which makes the affected operator do the opposite of what it’s supposed to do. In this case, the ! causes the -d operator to check for the absence of the graphics directory. To make this work properly, I also had to change the || operator to the && operator. (Also, note that there must be a blank space between the ! and the -d.)
You can also test for numerical values, like this:
[ $var -eq 0 ]You see that I’m calling up the value of the variable var, and testing to see if it is equal (-eq) to 0. Instead of using a negation (!) here to see if the variable is not equal to 0, use the -ne operator. Let’s see how that looks in the test_var.sh script:
#!/bin/bashvar1=0var2=1[ $var1 -eq 0 ] && echo "$var1 is equal to zero."[ $var2 -ne 0 ] && echo "$var2 is not equal to zero."Now, let’s run it:
[donnie@fedora ~]$ ./test_var.sh0 is equal to zero.1 is not equal to zero.[donnie@fedora ~]$The third way to perform a test is to use an if. . .then construct, which we’ll briefly talk about next.
Using an if. . .then Construct
Using an if. . .then construct is handy when you have more complex test conditions. Here’s the most basic example, in the form of the test_graphics_3.sh script:
#!/bin/bashcdpwdif [ ! -d graphics ]; then mkdir graphicsficd graphicspwdThis construct begins with the if statement, and ends with the fi statement. (That’s if spelled backwards.) Place a semi-colon after the test condition, followed by the keyword then. After that, specify the action that you want to perform, which in this case is mkdir graphics. Although indenting the action block isn’t necessary in shell scripting, as it is in other languages, it does help make the script more readable.
Of course, there’s a lot more to if. . .then constructs than just this. Not to worry though, because I’ll show you more about them in the Understanding Decisions and Loops section. Before we get there though, I want to show you some more concepts that you can use to fancy up your if. . .then constructs.
Now, let’s look at the various other types of tests that you can do.
Using Other Types of Tests
There are a lot more kinds of tests that you can do, including text string comparisons, numerical comparisons, whether files or directories exist and what permissions are set on them. Here’s a chart of the more popular tests, along with their operators:
| Operator | Test |
|---|---|
| -b filename | True if a block device file with the specified filename exists. |
| -c filename | True if a character device file with the specified filename exists. |
| -d directory_name | True if a directory with the specified directory name exists. |
| -e filename | True if any type of file with the specified filename exists. |
| -f filename | True if a regular file with the specified filename exists. |
| -g filename | True if a file or directory has the SGID permission set. |
| -G filename | True if a file exists and is owned by the Effective Group ID |
| -h filename | True if the file exists and it’s a symbolic link |
| -k filename | True if the file or directory exists and has the sticky bit set |
| -L filename | True if the file exists and it’s a symbolic link. (This is the same as -h.) |
| -p filename | True if the file exists and it’s a named pipe |
| -O filename | True if the file exists and it’s owned by the Effective UID |
| -r filename | True if the file exists and it’s readable |
| -S filename | True if the file exists and it’s a socket |
| -s filename | True if the file exists and it’s non-zero bytes in size |
| -u filename | True if the file exists and it has the SUID bit set |
| -w filename | True if the file exists and it’s writable |
| -x filename | True if the file exists and it’s executable |
| file1 -nt file2 | True if file1 is newer than file2 |
| file1 -ot file2 | True if file1 is older than file2 |
| -z string | True if the length of the text string is 0 |
| -n string | True if the length of the text string is not 0 |
| string1 == string2 | True if the two text strings are identical |
| string1 != string2 | True if the two text strings are not identical |
| string1 < string2 | True if string1 comes before string2 in alphabetical order |
| string1 > string2 | True if string1 comes after string2 in alphabetical order |
| integer1 -eq integer2 | True if the two integers are equal |
| integer1 -ne integer2 | True if the two integers are not equal |
| integer1 -lt integer2 | True if integer1 is less than integer2 | | integer1 -gt integer2 | True if integer1 is greater than integer2 | | integer1 -le integer2 | True if integer1 is less than or equal to integer2 | | integer1 -ge integer2 | True if integer1 is greater than or equal to integer2 | | -o optionname | True if a shell option is enabled |
I know, that’s a lot of stuff, isn’t it? But, that’s okay. If you don’t want to memorize all of this, just keep this chart handy for ready reference.
Next up, let’s talk about subshells.
Understanding Subshells
When you perform a test using the [ $var -ne 0 ] construct, the test will invoke a subshell. To prevent a test from invoking a subshell, use this construct, instead:
[[ $var -ne 0 ]]This can make your script run somewhat more efficiently, which might or might not be a huge deal for your particular script.
This
[[…]]type of construct is also necessary when you perform tests that require matching a pattern to a regular expression. (Matching regular expressions won’t work within a [ … ] construct.)The downside of this
[[…]]construct is that you can’t use it on certain non-bash shells, such as dash, ash, or Bourne. (You’ll see that in Chapter 19, Shell Script Portability.)Of course, you don’t know what regular expressions are just yet, and that’s okay. I’ll show you all about them in Chapter 9, Filtering Text with grep, sed, and Regular Expressions.
At any rate, you can always try your scripts with subshells and without subshells, to see which works better for you.
We’ve now looked at all three methods to perform testing. So, how about a bit of practice with a hands-on lab?
Hands-on Lab – Testing Conditions
For this step, download the tests-test.sh script from the Github repository. (It’s a rather long script that I can’t reproduce here, due to book formatting considerations.) Open the script in your text editor, and examine how it’s constructed. The first thing you’ll see is that it’s checking for the existence of the myfile.txt file, like this:
#!/bin/bash[ -f myfile.txt ] && echo "This file exists." || echo "This file does not exist."After that, you’ll see the command to create the file if it doesn’t exist, like this:
echo "We will now create myfile.txt if it does not exist, and make it with only read permissions for $USER."[ -f myfile.txt ] || touch myfile.txtNext, you’ll see the command to set 400 as the permissions setting, which means that the user has permission to read the file, and that nobody has permission to write to it. Then, we want to verify that all write permissions have been removed. Here’s how that looks:
chmod 400 myfile.txtls -l myfile.txtechoecho "We will now see if myfile.txt is writable."[ -w myfile.txt ] && echo "This file is writable." || echo "This file is not writable."After several more permissions settings manipulations and tests for them, you’ll see this stanza that tests for the existence of a directory, and creates it if it doesn’t exist:
[ -d somedir ] || echo "somedir does not exist."[ -d somedir ] || mkdir somedir && echo "somedir has just been created."ls -ld somedirThe final thing you’ll see is the stanza that tests for the noclobber option, sets it, and then tests for it again.
After you’ve finished reviewing the script, run it to see what happens.
For bonus points, retype the script into your own script file. Why? Well, a dirty little secret is that if you type code in yourself, it will help you better understand the concepts.
For the next step, create the tests-test_2.sh script with the following contents:
#!/bin/bashecho "We will now compare text strings."string1="abcd"string2="efgh"[[ $string1 > $string2 ]] && echo "string1 comes after string2 alphabetically." || echo "string1 comes before string2 alphabetically."echoecho "We will now compare numbers."num1=10num2=9Make the script file executable and then run it to view the results. Change the values of the string1, string2, num1, and num2 variables and then run the script again and view the results.
End of lab.
Next, let’s take a closer look at variables.
Understanding Scripting Variables
I’ve already told you a bit about scripting variables, and you’ve already seen them in use. But, there’s a bit more to the story.
Creating and Deleting Variables
As you’ve already seen, it’s sometimes either necessary or more convenient to define variables in your scripts. You can also define, view, and unset variables from the command-line. Here’s an example:
[donnie@fedora ~]$ car=Ford[donnie@fedora ~]$ echo $carFord[donnie@fedora ~]$ unset car[donnie@fedora ~]$ echo $car[donnie@fedora ~]$Here, I’ve defined the variable car, and set its value to Ford. The first echo command shows the assigned value. The second echo command verifies that I’ve successfully cleared the variable with unset.
Understanding Variables and Shell Levels
When you place a shebang line, such as #!/bin/bash or #!/bin/sh, at the start of your script, a new non-interactive child shell will be invoked every time you run the script. When the script finishes, the child shell terminates. The child shell inherits any variables that are exported from the parent shell. But, the parent shell won’t inherit any variables from the child shell. To demonstrate, let’s set the car variable to Volkswagen in the parent shell, like so:
[donnie@fedora ~]$ export car="Volkswagen"[donnie@fedora ~]$ echo $carVolkswagen[donnie@fedora ~]$Next, create the car_demo.sh script, like so:
#!/bin/bashecho \$car is set to \$carexport car=Toyotaecho "The \$car is very fast."echo \$car is set to \$carMake the file executable and then run the script. The output should look like this:
[donnie@fedora ~]$ ./car_demo.sh$car is set to VolkswagenThe Toyota is very fast.$car is set to Toyota[donnie@fedora ~]$Note how the Volkswagen value of car was inherited from the parent shell. That’s because I used the export command to make sure that this value would be available to the child shell that the script invokes. Let’s try this again, except this time, I won’t export the variable:
[donnie@fedora ~]$ unset car[donnie@fedora ~]$ car=Studebaker[donnie@fedora ~]$ ./car_demo.sh$car is set toThe Toyota is very fast.$car is set to Toyota[donnie@fedora ~]$To make this work, I first had to unset the car variable. In addition to clearing out the value of car, it also cleared out the export. When I ran the script this time, it couldn’t find the value of car that I set in the parent shell.
So, why is this important? It’s just that you may, at times, find yourself writing scripts that will call another script, which will effectively open another child shell. If you want variables to be available to a child shell, you have to export them.
Understanding Case Sensitivity
Section titled “Understanding Case Sensitivity”Variable names are case sensitive. So, a variable named car is completely different from variables named Car or CAR.
Environmental variables have names with all upper-case letters, and it’s best practice for programming variable names to be in either all lower-case letters or mixed-case letters. Amazingly, Linux and Unix shells don’t enforce that rule for programming variables. But, it is best practice, because it helps prevent you from accidentally overwriting the value of an important environmental variable.
Sad to say, there are shell scripting tutorials on the web in which the authors have you create programming variable names with all upper-case letters. In fact, I just came across one such tutorial. For the most part, the author has you create variables with names that don’t conflict with any environmental variables. In one spot though, the author has you create the USER variable and assign a value to it. Of course, USER is already the name of an environmental variable, so assigning a new value to it will overwrite what its value should be. The lesson here is that there are a lot of good tutorials on the web, but there are also a lot that give out wrong information.
Understanding Read-Only Variables
You’ve just seen that when you declare a variable in the normal way, you can either unset it or give it a new value. You can also make a variable read-only, which prevents the variable from being either redefined or unset. Here’s how that works:
[donnie@fedora ~]$ car=Nash[donnie@fedora ~]$ echo $carNash[donnie@fedora ~]$ readonly car[donnie@fedora ~]$ unset carbash: unset: car: cannot unset: readonly variable[donnie@fedora ~]$ car=Hudsonbash: car: readonly variable[donnie@fedora ~]$With the read-only property set, the only way that I can either change or get rid of car is to close the terminal window.
Well, this is the only way that you can get rid of a read-only variable if you don’t have root user privileges. If you do have root user privileges, you can use the GNU bash Debugger (gbd) to get rid of it. But, that’s beyond the scope of this chapter. (We’ll look at gbd in Chapter 21, Debugging Shell Scripts.)
Okay, this is all great if all you need is to define some individual variables. But, what if you need a whole list of variables? Well, this is where arrays come in handy. Let’s look at that next.
Understanding Array Variables
An array allows you to collect a list into one variable. The easy way to create an array variable is to assign a value to one of its indices, like so:
name[index]=valueHere, name is the name of the array, and index is the position of the item in the array. (Note that index must be a number.) value is the value that’s set for that individual item in the array.
The numbering system for arrays begins with 0. So, name[0] would be the first item in the array. To create an indexed array, use declare with the -a option, like so:
[donnie@fedora ~]$ declare -a myarray[donnie@fedora ~]$Next, let’s create the list that will be inserted into the array, like so:
[donnie@fedora ~]$ myarray=(item1 item2 item3 )[donnie@fedora ~]$You can view the value of any individual item in the array, but there’s a special way to do it. Here’s what it looks like:
[donnie@fedora ~]$ echo ${myarray[0]}item1[donnie@fedora ~]$ echo ${myarray[1]}item2[donnie@fedora ~]$ echo ${myarray[2]}item3[donnie@fedora ~]$Note how I had to surround the myarray[x] construct with a pair of curly braces.
To view the whole list of array items, use either a * or an @ in place of the index number, like so:
[donnie@fedora ~]$ echo ${myarray[*]}item1 item2 item3[donnie@fedora ~]$ echo ${myarray[@]}item1 item2 item3[donnie@fedora ~]$To just count the number of array items, insert a # in front of the array name, like this:
[donnie@fedora ~]$ echo ${#myarray[@]}3[donnie@fedora ~]$ echo ${#myarray[*]}3[donnie@fedora ~]$Okay, that covers the basics of arrays. Let’s do something a bit more practical with a hands-on lab.
Hands-on Lab — Using Arrays
- To see how arrays are built, create the ip.sh script with the following contents:
#!/bin/bashecho "IP Addresses of intruder attempts"declare -a ipip=( 192.168.3.78 192.168.3.4 192.168.3.9 )echo "ip[0] is ${ip[0]}, the first item in the list."echo "ip[2] is ${ip[2]}, the third item in the list."echo "*********************************"echo "The most dangerous intruder is ${ip[1]}, which is in ip[1]."echo "*********************************"echo "Here is the entire list of IP addresses in the array."echo ${ip[*]}- Make the file executable and run it.
chmod u+x ip.sh./ip.sh- Create the /opt/scripts/ directory to store data files that your scripts will need to access, like this:
sudo mkdir /opt/scripts- In the /opt/scripts/ directory, create the banned.txt file. (Note that in this directory, you’ll need to use sudo when opening your text editor.) Add to it the following contents:
192.168.0.4824.190.78.10138.101.148.12641.206.45.20258.0.0.0/859.107.0.0/1759.108.0.0/1559.110.0.0/1559.151.0.0/1759.155.0.0/1659.172.0.0/15- In your own home directory, create the attackers.sh script, which will build an array of banned IP addresses from a list in a text file. Add the following contents:
#!/bin/bashbadips=$(cat /opt/scripts/banned.txt)declare -a attackersattackers=( $badips )echo "Here is the complete list: "echo ${attackers[@]}echo193
echo "Let us now count the items in the list."num_attackers=${#attackers[*]}echo "There are $elements IP addresses in the list."echoecho "attackers[2] is ${attackers[2]}, which is the third address in thelist."exit- Set the executable permission and run the script, like so:
chmod u+x attackers.sh./attackers.sh- Modify the script so that the elements 0, 5, and 8 are printed to screen, and rerun the script. (You’ve already seen how to do it)
End of Lab
A few words of explanation about this attackers.sh script are in order. First, in the second line, I’m using command substitution with the cat command to assign the contents of the banned.txt script to the badips variable. (I know, I keep showing you examples of command substitution, but I haven’t fully explained it yet. Don’t worry though, I’ll do that in a bit.) However, this still isn’t an array. I’ve created that separately in the declare -a line. In the attackers= line, I called back the value of the badips variable, which I then used to build the attackers array. Alternatively, I could have skipped using the intermediate variable and built the array directly from the cat command substitution, as I did in this attackers_2.sh script:
#!/bin/bashdeclare -a badipsbadips=( $(cat /opt/scripts/banned.txt) )echo "Here is the complete list: "echo ${badips[@]}echoecho "Let us now count the items in the list."elements=${#badips[*]}echo "There are $elements IP addresses in the list."echoecho "badips[2] is ${badips[2]}, which is the third address in the list."exitEither way works, but this way is a bit more streamlined.
In a real-life scenario, you could add code that will automatically invoke a firewall rule that will block all of the addresses in the banned.txt file. But, that requires using techniques that I haven’t yet shown you. So, we’ll just have to get that later.
Next, let’s expand some variables.
Understanding Variable Expansion
Variable expansion, which is also called parameter expansion, allows the shell to test or modify values of a variable to be used in a script, using special modifiers enclosed in curly braces and preceded by a {variable}). If this variable is not set in bash it will be expanded to a null string. The best way to begin is to show you a few simple examples.
Substituting a Value for an Unset Variable
First, I’ll define the cat variable with the name of my 16-year old gray kitty. Then, I’ll perform a test to see if cat really has a set value, like this:
[donnie@fedora ~]$ cat=Vicky[donnie@fedora ~]$ echo ${cat-"This cat variable is not set."}Vicky[donnie@fedora ~]$Next, I’ll unset the value of cat, and perform the test again. Watch what happens:
[donnie@fedora ~]$ unset cat[donnie@fedora ~]$ echo ${cat-"This cat variable is not set."}This cat variable is not set.[donnie@fedora ~]$So, what happened? Well, the - between cat and “This cat variable is not set.” tests to see whether or not the cat variable has an assigned value. If the variable has no assigned value, then the text string that comes after the - is substituted for the variable’s value. However, the substituted value is not actually assigned to the variable, as you see here:
[donnie@fedora ~]$ echo $cat[donnie@fedora ~]$Now, assign a null value to cat, and try this again:
donnie@fedora:~$ cat=donnie@fedora:~$ echo ${cat-"This cat variable is not set."}donnie@fedora:~$This time, we just get a blank line as output, because the cat variable is set. It’s just that it’s set to a null value. Let’s try this again, using : - instead of - , like so:
donnie@fedora:~$ echo ${cat:-"This cat variable is not set."}This cat variable is not set.donnie@fedora:~$This works because placing a : in front of the - causes variables that have been set with a null value to be treated as unset variables.
Okay, that does it for unset variables. Sometimes though, we might need to work with variables that do have set values, as you’ll see next.
Substituting a Value for a Set Variable
Section titled “Substituting a Value for a Set Variable”You can go the opposite way by substituting a value for a variable that does have an assigned value, like this:
[donnie@fedora ~]$ car="1958 Edsel Corsair"[donnie@fedora ~]$ echo ${car+"car is set and might or might not be null"}car is set and might or might not be null[donnie@fedora ~]$In this case, the + construct causes the following text string to be substituted for the variable’s assigned value. Note that since there are no special characters in this text string that need to be escaped, the quotes are optional. However, best practice dictates using quotes anyway, just to be safe. Also note that this substitution did not change the actual assigned value of the car variable, as you see here:
[donnie@fedora ~]$ echo $car1958 Edsel Corsair[donnie@fedora ~]$As you just saw with the - operator, the + operator treats variables with a null value as being set. If you want to treat variables with null values as unset, then use the :+ operator. If you create a variable and leave it with a null value, it will look something like this:
[donnie@fedora ~]$ computer=[donnie@fedora ~]$ echo ${computer:+"computer is set and is not null"}[donnie@fedora ~]$You see that with a null value, there’s no output from the echo command. Now, since I just happen to be using a Dell computer, let’s set the value of computer to Dell, as you see here:
[donnie@fedora ~]$ computer=Dell[donnie@fedora ~]$ echo ${computer:+"computer is set and might or might not be null"}computer is set and might or might not be null[donnie@fedora ~]$As I’ve already indicated, the operators that we’ve just looked at will substitute a value for a variable, depending upon whether the value has an assigned value. But, they won’t actually change the value of the variable. But, we might at times need to change a variable’s value, as we’ll see next.
Assigning a Value to a Variable
This next trick actually will assign a value to an unset variable, using the = and := operators. Let’s begin by assigning a value to the town variable:
donnie@fedora:~$ unset towndonnie@fedora:~$ echo $towndonnie@fedora:~$ echo ${town="Saint Marys"}Saint Marysdonnie@fedora:~$ echo $townSaint Marysdonnie@fedora:~$Now, let’s see if we can assign a different value to town:
donnie@fedora:~$ echo ${town="Kingsland"}Saint Marysdonnie@fedora:~$ echo $townSaint Marysdonnie@fedora:~$As you’ve seen before, using this operator without a preceding : causes a variable with a null value to be treated as a set variable. Here’s how that looks:
donnie@fedora:~$ unset towndonnie@fedora:~$ town=donnie@fedora:~$ echo ${town="Saint Marys"}donnie@fedora:~$To show how using the := operator works, let’s create the armadillo variable with a null value, and then assign to it a default value, like so:
[donnie@fedora ~]$ armadillo=[donnie@fedora ~]$ echo ${armadillo:=Artie}Artie[donnie@fedora ~]$ echo $armadilloArtie[donnie@fedora ~]$Artie is the tentative name that I’ve given to the armadillo who’s recently begun visiting my back yard at night. But, I don’t yet know if the armadillo is a boy or a girl, so I don’t yet know if Artie is an appropriate name. If I find out that it’s a girl, I might want to change the name to Annie. So, let’s try the preceding exercise again, but with armadillo set to Annie. Then, we’ll see if we can use our variable expansion to change it to Artie, like so:
[donnie@fedora ~]$ armadillo=Annie[donnie@fedora ~]$ echo ${armadillo:=Artie}<!-- page: 208 (printed 197) -->Annie[donnie@fedora ~]$ echo $armadilloAnnie[donnie@fedora ~]$You see that since the armadillo variable already had the Annie assigned as its value, the echo ${{armadillo:=Artie}} command had no effect, other than to show the value that I had already assigned.
Now, what if you don’t want to substitute a variable’s value, but just want to see an error message? Let’s look at that.
Displaying an Error Message
You won’t always want to perform either a value substitution or a value assignment for an unset variable. Sometimes, you might just want to see an error (stderr) message if the variable is unset. Do that with the :? construct, like this:
[donnie@fedora ~]$ dog=[donnie@fedora ~]$ echo ${dog:?The dog variable is unset or null.}bash: dog: The dog variable is unset or null.[donnie@fedora ~]$Let’s try that again with a dog named Rastus, which was the name of an English Shepard that my Grandma had when I was a kid. It will look like this:
[donnie@fedora ~]$ dog=Rastus[donnie@fedora ~]$ echo ${dog:?The dog variable is unset or null.}Rastus[donnie@fedora ~]$I know, you’re thinking that this looks just like the first example, where I substituted a message for the value of the unset cat variable with a -. Well, you’re kind of right. It’s just that the - substitutes a value that shows up as stdout, while the :? substitutes a message that shows up as stderr. Another difference is that if you use :? in a shell script with an unset variable, it will cause the script to exit.
Try that by creating the ex.sh script with the following contents:
#!/bin/bashvar=: ${var:?var is unset, you big dummy}echo "I wonder if this will work."So far, I’ve been showing you how to use echo to both perform the variable expansion and show the results. This particular construct allows you to just test the variable without echoing the results, by using a : instead of echo. Now when I run this script, you’ll see that it exits before the final echo command can execute, as you see here:
[donnie@fedora ~]$ ./ex.sh<!-- page: 209 (printed 1) -->./ex.sh: line 3: var: var is unset, you big dummy[donnie@fedora ~]$Wait a minute! Did I just call myself a big dummy? Oh, well. Anyway, let’s change the script so that var has an assigned value, as you see in this ex_2.sh script:
#!/bin/bashvar=somevalue: ${var:? "var is unset, you big dummy"}echo "I wonder if this will work with a value of "$var"."The script now runs to completion, as you see here:
donnie@fedora:~$ ./ex_2.shI wonder if this will work with a value of somevalue.donnie@fedora:~$So to reiterate, using the : in place of the echo prevents the ${var:? “var is unset, you big dummy”} construct from printing out the value of the variable. We can change that behavior by changing the : back to an echo, as you see here in ex_3.sh:
#!/bin/bashvar=somevalueecho ${var:? "var is unset, you big dummy"}echo "I wonder if this will work with a value of "$var"."Now, let’s see the results of that change:
donnie@fedora:~$ ./ex_3.shsomevalueI wonder if this will work with a value of somevalue.donnie@fedora:~$This time, the value of var does print out.
As you’ve just seen with the - and the + operators, preceding the ? with a : causes the operator to treat a variable that was created with a null value as unset. Leaving out the : causes the operator to treat variables that were created with a null value as set.
Now, let’s change gears by looking at variable offsets.
Using Variable Offsets
The last type of variable expansion that I’ll show you involves the substitution of just a subset of a text string. This involves using a variable offset, and is a bit more difficult to understand unless you can see an example.
When you set a variable it will have a set size, or number of characters. The {variable:offset:length} construct allows you to also determine how many characters that you want to use. To begin, let’s create the text variable with a value of MailServer, like so:
[donnie@fedora ~]$ text=MailServer[donnie@fedora ~]$ echo $textMailServer[donnie@fedora ~]$Now, let’s say that we only want to see the text that comes after the fourth letter. Use an offset, like this:
[donnie@fedora ~]$ echo ${text:4}Server[donnie@fedora ~]$Cool, it works. Now, let’s say that we want to see just the first four letters. Use an offset and length, like this:
[donnie@fedora ~]$ echo ${text:0:4}Mail[donnie@fedora ~]$This means that we’re starting after position 0, and are viewing only the first four letters.
You can also extract text from somewhere in the middle of the text string, like so:
[donnie@fedora ~]$ echo ${text:4:5}Serve[donnie@fedora ~]$Here, I’m starting after the fourth character, and am extracting the next five characters.
For something a bit more practical, let’s set the location variable with the name of a US city and state, along with its associated zip code. (That’s postal code for anyone who isn’t here in the US.) Then, let’s say that we want to extract the zip code portion of the text string, like so:
[donnie@fedora ~]$ location="Saint Marys GA 31558"[donnie@fedora ~]$ echo "Zip Code: ${location:14}"Zip Code: 31558[donnie@fedora ~]$Instead of setting the offset by counting from the beginning of the text string, I could also have used a negative number to just extract the last part of the text string. Since the zip code is five digits long, I could use a -5, like this:
[donnie@fedora ~]$ echo "Zip Code: ${location: -5}"<!-- page: 211 (printed 1) -->Zip Code: 31558[donnie@fedora ~]$To ensure that this always works properly, be sure to always leave a blank space between the : and the -. Also, since city names will always vary in length, this would be a better option if you need to extract zip codes from a whole list of locations.
That’s it for offsets. So now, let’s match some patterns.
Matching Patterns
The next variable expansion trick involves matching patterns. Let’s start by creating the pathname variable, like so:
[donnie@fedora ~]$pathname="/var/lib/yum"[donnie@fedora ~]$Now, let’s say that I want to strip the lowest level directory from this path. I’ll do that with a % and an *, like so:
[donnie@fedora ~]$echo ${pathname%/*yum*}/var/lib[donnie@fedora ~]$The % tells the shell to omit the final part of the string that matches the pattern. In this case, the * at the end isn’t necessary, because yum just happens to be at the end of the pathname. So, you’ll get the same result without it. But, if you want to omit the lowest two levels of pathname, you will need to use the * so that the pattern will match properly. Here’s what I’m talking about:
[donnie@fedora ~]$echo ${pathname%/*lib}/var/lib/yum[donnie@fedora ~]$echo ${pathname%/*lib*}/var[donnie@fedora ~]$You see that without the *, the pattern matching didn’t work. With the *, the matching worked just fine. So, even when the * isn’t absolutely necessary, it’s best to include it, just to be sure.
On the other hand, you might at times just want to extract the names of the lower level directories. To do that, just replace the % with a #, like so:
[donnie@fedora ~]$echo ${pathname#/var}/lib/yum[donnie@fedora ~]$echo ${pathname#/var/lib}/yum<!-- page: 212 (printed 201) -->[donnie@fedora ~]$Let’s wrap this section up with one final trick. This time, I’ll match a pattern and then substitute something else. First, I’ll create the string variable, like so:
[donnie@fedora ~]$ string="Hot and Spicy Food"[donnie@fedora ~]$ echo $stringHot and Spicy Food[donnie@fedora ~]$That’s good, except that I’ve decided that I don’t want blank spaces between the words. So, I’ll substitute an _ character, like so:
[donnie@fedora ~]$ echo ${string/[[ :space:]]/_}Hot_and Spicy Food[donnie@fedora ~]$That didn’t work out so well, because it only replaced the first blank space. To perform a global replacement, I’ll need to add an extra forward slash after string, like this:
[donnie@fedora ~]$ echo ${string//[[ :space:]]/_}Hot_and_Spicy_Food[donnie@fedora ~]$This looks much better. But, what’s really going on here? Well, we’re using a /pattern_to_be_replaced/ construct to perform the substitution. Whatever you place between the two forward slashes is what you want to replace. You can specify an individual character, a character class, or some other pattern that you want to replace. At the end, between the last forward slash and the closing curly brace, place the character that you want to substitute.
There’s still a bit more to the variable expansion business, but I’ve shown you the most practical examples. If you want to see more, you’ll find a reference in the Further Reading section.
Okay, now that we’ve substituted some patterns, let’s move on to substituting commands.
Understanding Command Substitution
In the Counting Logged-in Users and Using Arrays Hands-on Labs, I’ve shown you some examples of command substitution in action, but I haven’t yet fully explained it. It’s about time that I do.
Command substitution is an extremely handy tool that you will use extensively. I mean, really. You can do some very cool stuff with it. It involves taking the output from a shell command and either using it in another command, or assigning it as the value of some variable. You’ll place the command from which you’ll be taking output within a $( ) construct. Here’s a very simple example:
[donnie@fedora ~]$ echo "This machine is running kernel version $(uname -r)."This machine is running kernel version 6.5.5-200.fc38.x86_64.[donnie@fedora ~]$You see how the output of the uname -r command, which shows the version of the current running Linux kernel, is substituted for the command substitution construct.
Now, let’s create the command_substitution_1.sh script, and make it look like this:
#!/bin/bash[[ ! -d Daily_Reports ]] && mkdir Daily_Reportscd Daily_Reportsdatestamp=$(date +%F)echo "This is the report for $datestamp" > daily_report_$datestamp.txtHere’s the breakdown. In the second line, I’m testing for the absence of the Daily_Reports directory. If it’s not there, then I’ll create it. In the fourth line, I’m using command substitution to create the datestamp variable with the current date as its assigned value. The current date is returned by the date +%F command, and will be in the year-month-day format (2023-10-03). In the final line, I’m echoing a message that contains today’s date into a file that contains today’s date in its filename. Here’s what that looks like:
[donnie@fedora ~]$ ls -l Daily_Reports/total 4-rw-r--r--. 1 donnie donnie 34 Oct 3 15:30 daily_report_2023-10-03.txt[donnie@fedora ~]$ cat Daily_Reports/daily_report_2023-10-03.txtThis is the report for 2023-10-03[donnie@fedora ~]$Is that slick, or is that slick? Trust me, you’ll be doing this sort of thing a lot if you need to create scripts that will automatically generate reports.
Tip There are many different formatting options that you can use with the date command. To see them all, just view the date man page.
But, we’re missing an important element here. What if today’s report has already been created? Do you want to overwrite it?
No, in this case, I don’t. So, let’s create the command_substitution_2.sh script to test for the absence of today’s report before creating another one. It involves adding just a teeny bit of extra code, like this:
#!/bin/bash[[ ! -d Daily_Reports ]] && mkdir Daily_Reportscd Daily_Reportsdatestamp=$(date +%F)[[ ! -f daily_report_$datestamp.txt ]] && echo "This is the report for$datestamp" > daily_report_$datestamp.txt || echo "This report has already beendone today."That last command that looks like three lines is really just one line that wraps around on the printed page.
Now, prepare to be amazed at what happens when I run this new, modified script:
[donnie@fedora ~]$ ./command_substitution_2.shThis report has already been done today.[donnie@fedora ~]$Just for fun, let’s look at some other cool examples.
Let’s create a script, which we’ll call am_i_root_1.sh, which will look like this:
#!/bin/bashtest $(whoami) != root && echo "You are not the root user."test $(whoami) == root && echo "You are the root user."The whoami command returns the name of the user who’s running the command. Here’s what that looks like when I run it first without sudo, and then with sudo:
[donnie@fedora ~]$ whoamidonnie[donnie@fedora ~]$ sudo whoamiroot[donnie@fedora ~]$As you see, running whoami with sudo shows that I’m the root user. The first command uses the != operator to test if the user is not the root user. The second command uses the == operator to test if the user is the root user. Now, let’s run the script to see what happens:
[donnie@fedora ~]$ ./am_i_root_1.shYou are not the root user.[donnie@fedora ~]$ sudo ./am_i_root_1.sh[sudo] password for donnie:You are the root user.[donnie@fedora ~]$It works, which means that we have achieved coolness. But, we can be even more cool by streamlining things a bit. Modify the script so that it looks like this:
#!/bin/bashtest $(whoami) != root && echo "You are not the root user." || echo "You are the root user."two commands in this script, I now have only one. But either way, the output is identical. Instead of placing your command within a $( ) construct, you can also surround it with a pair of backticks, like this:
[donnie@fedora ~]$ datestamp=`date +%F`[donnie@fedora ~]$ echo $datestamp2023-10-03[donnie@fedora ~]$That works, but it’s a deprecated method that I don’t recommend. The biggest problem with it is that if your command contains any special characters that the shell might interpret incorrectly, you’ll have to be sure to escape them with a backslash. With the newer $( ) construct, you don’t have to worry so much about that. I’m only mentioning this method because you might still see other people’s scripts that use it.
That does it for the command substitution business. Now, we need to make some decisions.
Understanding Decisions and Loops
So far, I’ve been showing you a lot of programming techniques and constructs that are specific to shell scripting. In this section, I’ll show you some constructs that are common to most all programming languages. I’ll begin by showing you another way to make decisions.
The if . then Construct
Although the && and || decision constructs work for simple scripts, you might want to use if . then constructs for anything more complex, such as when you would need to test for multiple conditions at once. For the first example, create the am_i_root_2.sh script, which will look like this:
#!/bin/bashif [ $(id -u) == 0 ]; then echo "This user is root."fiif [ $(id -u) != 0 ]; then echo "This user is not root." echo "This user's name is $(id -un)."fiNote that each decision stanza begins with if and ends with fi. (Yes, that’s if spelled backwards.) Also note that with bash shell scripting, indentation isn’t required, as it is in certain other programming languages. But, it does make the code much more readable.
Instead of using the whoami command this time, I’m using the id command, which offers more options than whoami. (See the man pages for both commands for details.) As far as the rest of it goes, rather than trying to explain it all in detail, I’ll just let you study this script to see how everything works. That will be easier for me, and less boring for you. And besides, I have faith in you.
Now, let’s see what happens when I run this script:
[donnie@fedora ~]$ ./am_i_root_2.shThis user is not root.This user's name is donnie.[donnie@fedora ~]$[donnie@fedora ~]$ sudo ./am_i_root_2.shThis user is root.[donnie@fedora ~]$When you’re testing for more than one condition for the same decision, it would be more proper to use one if .. then .. elif construct, rather than two if .. then constructs. This can add a bit more clarity to your code, so that anyone who reads it can make a bit more sense of it. Let’s create the am_i_root_3.sh script to showcase this technique. Make it look like this:
#!/bin/bashif [ $(id -u) == 0 ]; then echo "This user is root."elif [ $(id -u) != 0 ]; then echo "This user is not root." echo "This user's name is $(id -un)."fiThe elif keyword in this script is short for else if. Other than that, everything is pretty much the same as it was before in the previous script. When you run it, you’ll get the same output as you got for the previous script. Also, note that you can test for multiple conditions with more than one elif stanza.
Alternatively, you could also use an if .. then .. else construct. Create the am_i_root_4.sh script, which will look like this:
#!/bin/bashif [ $(id -u) == 0 ]; then echo "This user is root."else echo "This user is not root." echo "This user's name is $(id -un)."fiUsing else can be handy, because it defines a default action to take if the conditions in any of the if or elif stanzas aren’t fulfilled. For example, take a look at this script that detects which operating system your machine is running:
#!/bin/bashos=$(uname)if [[ $os == Linux ]]; then echo "This machine is running Linux."elif [[ $os == Darwin ]]; then echo "This machine is running macOS."elif [[ $os == FreeBSD ]]; then echo "This machine is running FreeBSD."else echo "I don't know this $os operating system."fiYou see that this script can detect Linux, macOS, or FreeBSD. If the machine isn’t running any of those three operating systems, the else statement at the end displays the default message. Another thing to note is that you’ll need to place a semi-colon and a then keyword at the end of each if or elif statement, but you don’t need to place them after an else statement.
Here’s how that looks when I run the script on an OpenIndiana machine:
donnie@openindiana:~$ ./os-test.shI don't know this SunOS operating system.donnie@openindiana:~$Of course, if I wanted to, I could insert another elif stanza to test for SunOS.
That about covers it for if. .then. Let’s now do something while waiting for something else.
The do . while construct
This construct will continuously execute a set of commands while a certain condition is true. Here’s an example:
#!/bin/bashx=10while [[ $x -gt 0 ]]; do x=$(expr $x - 1) echo $xdoneThis while_demo.sh script starts by assigning a value of 10 to the x variable. As long as the value of x remains greater than 0, it will subtract 1 from this value and assign the new value to x, using the expr $x-1 command. It then echoes the new value. The output looks like this:
[donnie@fedora ~]$ ./while_demo.sh9876543210[donnie@fedora ~]$Note that in this while_demo.sh script, you can use a bit of shorthand for decrementing the value of x by 1 for each loop. Just replace the x=x - 1) line with:
((x--))This is the same type of construct that you might be used to seeing in C or C++ language programs. However, this construct is not portable, which means that it works fine on bash, but not on other shells. So, if you need to make your script so that it will run on Bourne shell, dash, or ash, you’ll need to avoid this construct and instead stick with the x=x - 1) construct.
You could also use a while loop to read a text file, line-by-line. Here’s the very simple read_file.sh script that reads the /etc/passwd file:
#!/bin/bashfile=/etc/passwdwhile read -r line; do echo $linedone < "$file"As you see, I start by creating the file variable with /etc/passwd as its assigned value. The while line defines the variable line, and the read -r command assigns values to the line variable. On each pass of the while loop, the read -r command reads one line of the file, assigns the contents of the line to the line variable, and then echos the contents of the line to stdout. When all lines of the file have been read, the loop terminates. At the end, you see that I’m using a stdin redirector to make the while loop read the file. Normally, read breaks long lines into shorter lines and terminates each part of the long line with a backslash. The -r option disables that behavior.
There may be times when you’ll want to create an infinite loop that never stops until you tell it to. (There might also be times when you’ll create an infinite loop by accident, but that’s a whole different story. For now, let’s assume that you want to do it on purpose.) To demonstrate, create the infinite_loop.sh script, and make it look like this:
#!/bin/bashwhile :do echo "This loop is infinite." echo "It will keep going until you stop it." echo "To stop it, hit Ctrl-c." sleep 1doneIt’s a rather useless script, which does nothing but echo some messages. The sleep 1 command causes a one-second delay between each iteration of the loop. Here’s what happens when I run this script:
[donnie@fedora ~]$ ./infinite_loop.shThis loop is infinite.It will keep going until you stop it.To stop it, hit Ctrl-c.This loop is infinite.It will keep going until you stop it.To stop it, hit Ctrl-c.^C[donnie@fedora ~]$There are still a few other tricks that we can do with while..do, but this will do it for now. Let’s now look at for..in.
The for..in Construct
The for . . in construct will process a list, and perform a command for each item in the list. In this car_demo_2.sh script, the for line creates the cars variable. Here’s what it looks like:
#!/bin/bashfor cars in Edsel Ford Nash Studebaker Packard Hudsondo echo "$cars"doneecho "That's all, folks!"Each time that the loop iterates, the in keyword takes a name of a classic car from the list, and assigns it to cars as its value. The loop ends when it reaches the end of the list. Here’s what happens when I run the script:
[donnie@fedora ~]$ ./car_demo_2.shEdselFordNashStudebakerPackardHudsonThat's all, folks![donnie@fedora ~]$That’s easy enough, so let’s try another one. This time, create the list_demo.sh script, like this:
#!/bin/bashfor filename in *do echo "$filename"doneThis loop just does an ls-style listing of the files in your current directory. I’m using the * wildcard to tell for to read in all of the filenames, regardless of how many files there are. In the echo line, I have to surround $filename with a pair of double quotes in case any filenames contain blank spaces. Here’s what happens when I run it:
[donnie@fedora ~]$ ./list_demo.sh15827_zip.zip2023-08-01_15-23-31.mp42023-08-01_16-26-12.mp42023-08-02_13-57-37.mp4......xargs_test.txtyad-form.shzoneinfo.zip[donnie@fedora ~]$The reason this works is that if you do echo * from the command-line, you’ll see a jumbled-up listing of files in the directory. The for . . in loop causes echo to list each filename on its own line.
Okay, we’ve just looked at for . . in. Let’s now look at for.
The for Construct
This is similar to the for . . in construct, except for where it gets its list. With for, the user will enter the list as arguments when calling the script. Let’s create the car_demo_3.sh script to demonstrate this:
#!/bin/bashfor carsdo echo "$cars"doneThe cars variable gets created in the for line, but there’s no list of cars. So, where does the list come from? It comes from arguments that the user enters on the command-line when he or she invokes the script. Instead of using classic car names this time, let’s use a list of modern car names, like so:
[donnie@fedora ~]$ ./car_demo_3.sh Toyota Volkswagen Subaru HondaToyotaVolkswagenSubaruHonda[donnie@fedora ~]$Next, let’s look at the break command.
Using break
Section titled “Using break”Use the break command to further control how you want for..in and while..do loops to operate. To see how this works, create the break_demo.sh script and make it look like this:
#!/bin/bashj=0while [[ $j -lt 5 ]]do echo "This is number: $j" j=$((j + 1)) if [[ "$j" == '2' ]]; then echo "We have reached our goal: $j" break fidoneecho "That's all, folks!"The while line tells the script to run as long as the value of j is less than 5. The j=$((j + 1)) construct on the sixth line is a mathematical operator, with increments the value of j by 1 on each iteration of the loop. The if..then construct that starts on the seventh line defines what should happen when the value of j is equal to 2. The break command then terminates the loop. Here’s how it looks:
[donnie@fedora ~]$ ./break_demo.shThis is number: 0This is number: 1We have reached our goal: 2<!-- page: 222 (printed 211) -->That's all, folks![donnie@fedora ~]$As I’ve indicated for the while_demo.sh script, you can replace the j=$((j + 1)) construct with:
((j++))
However, ((j++)) is bash-specific, and might not work on other non-bash shells.
You can also express this as j=$(expr j + 1), which is also portable, and is the form that I showed you in the while_demo.sh script.
(I’ll show you more about performing math in shell scripts in Chapter 11, Performing Mathematical Operations.)
Just for fun, delete the break command from the script and run it again. You should now see this:
[donnie@fedora ~]$ ./break_demo.shThis is number: 0This is number: 1We have reached our goal: 2This is number: 2This is number: 3This is number: 4That's all, folks![donnie@fedora ~]$This time, the loop keeps running past the number 2.
Now that we’ve taken a break, let’s continue.
Using continue
The continue command also modifies how for..in and while..do loops operate. This time, create the for_continue.sh script, and make it look like this:
#!/bin/bashfor cars in Pontiac Oldsmobile Buick Chevrolet Ford Mercurydo if [[ $cars == Buick || $cars == Mercury ]]; then continue fiecho $carsdoneOn each iteration of the for loop, a different classic car name gets assigned as the value of cars. The if..then stanza determines if the value of cars is either Buick or Mercury. The continue command within the if..then stanza causes the loop to skip over those two car names, so that the echo command won’t list them. You also see another use for the || construct here. When used within a test operation, the || acts as an or operator. Here’s what the output looks like:
[donnie@fedora ~]$ ./for_continue.shPontiacOldsmobileChevroletFord[donnie@fedora ~]$Next, let’s try this with a while..do loop. Create the while_continue.sh script, like this:
#!/bin/bashj=0while [[ $j -lt 6 ]]do j=$((j + 1)) [[ $j -eq 3 || $j -eq 6 ]] && continue echo "$j"doneThis time, we just want to skip over numbers 3 and 6. Here’s the output:
[donnie@fedora ~]$ ./while_continue.sh1245[donnie@fedora ~]$Okay, enough of that. Let’s look at the until construct.
The until Construct
The until loop will continue until a certain condition is met. You can use it for a variety of things, such as playing a guessing game. See how it works by creating the secret_word.sh script, like this:
#!/bin/bashsecretword=Donnieword=echo "Hi there, $USER!"echo "Would you like to play a guessing game?"echo "If so, then enter the correct secret word"echo "to win a special prize."echoechountil [[ "$word" = "$secretword" ]]do echo -n "Enter your guess. " read worddoneecho "Yay! You win a pat on the back!"So, I’ve set the secretword to Donnie. (Hey, that’s me!) I then set word to a null value. The until loop will run until I enter the correct value for secretword. (In this case, read pauses the script until you enter your guess.) It works like this:
[donnie@fedora ~]$ ./secret_word.shHi there, donnie!Would you like to play a guessing game?If so, then enter the correct secret wordto win a special prize.Enter your guess. VickyEnter your guess. CleopatraEnter your guess. DonnieYay! You win a pat on the back![donnie@fedora ~]$Cool, right? I mean, this is yet another trick that you can perform at your next party.
All right, let’s move on to the next one.
The case Construct
The case construct provides a way to avoid using an if..then..else construct. It allows users to enter a text string, then evaluate that string and provide the option that the string indicates. Here’s the basic structure of case:
case $variable inmatch_1)commands_to_execute;;match_2)commands_to_execute;;
<!-- page: 225 (printed 214) -->
match_3)commands_to_execute;;*) Optional Informationcommands_to_execute_for_no_match;;esacThe case statement is matched against a number of values until a match is found. When a match is found, the commands are executed until the double semicolons (;; ) are reached. Then, the commands after the esac line are executed.
If there is no match, then the commands between the *) and the double semicolons are executed. The *) acts the same way as the else in an if … then construct, in that they both provide a default action in case none of the tested conditions are met.
Just for fun, try this out by creating the term_color.sh script, which will look like this:
#!/bin/bashecho -n "Choose Background Color for Terminal(b-black,g-grey): "read colorcase "$color" inb)setterm -background black -foreground white;;g)setterm -background white -foreground black;;*)echo "I do not understand";;esacexitThis script allows you to change the background color of your terminal. (And yes, I know that I’ve set the g option to white. That’s because when you run this script and choose the g option, the background will look more gray than white.) Running the script looks like this:
[donnie@fedora ~]$ ./term_color.shChoose Background Color for Terminal(b-black,g-grey): g[donnie@fedora ~]$Run the script in your own terminal, choose the g option, and you should see the background of the command prompt turn gray. (Or, if your terminal is already set up with a white background, choose the b option, instead.) To see the background for the whole terminal turn gray, just type clear.
For even more fun, edit the script to add another option. First, make the echo line at the top look like this:
echo -n "Choose Background Color for Terminal(b-black,g-grey,y-yellow): "Then, add the y option after the g option. This new option will look like this:
y)setterm -background yellow -foreground red;;To see something that’s hideously ugly, run the script again and choose the y option. (Don’t worry though, because the setting isn’t permanent.) Here’s how using the various options will look:
Okay, you’ve already seen how to use for to enter arguments when you invoke your scripts. Now, let’s look at another way.
Using Positional Parameters
Section titled “Using Positional Parameters”When you run a shell script, you can also enter command-line parameters that will be used within the script. The first parameter that you enter will be designated as 2, and so on. (0 parameter is reserved for the name of the script.
To see how this works, create the position_demo.sh script, which will look like this:
#!/bin/bash# position_demoecho "I have a cat, whose name is $1."echo "I have another cat, whose name is $2."echo "I have yet another cat, whose name is $3."echoechoecho "The script that I just ran is $0"To invoke the script, enter three names after the name of the script, like this:
[donnie@fedora ~]$ ./position_demo.sh Vicky Cleopatra LionelI have a cat, whose name is Vicky.I have another cat, whose name is Cleopatra.I have yet another cat, whose name is Lionel.The script that I just ran is ./position_demo.sh[donnie@fedora ~]$In the output, the 2, and 0 variable will be expanded to the full path and name of the script.
There are three special positional parameters that you can use to enhance your scripts. Here’s the list:
- $#: This shows the number of parameters that you’ve entered.
- $@: This lists all of the parameters that you’ve entered, with each one on a separate line.
- $*: This lists all of the parameters that you’ve entered on a single line, with a blank space between each one.
One cool thing that you can do with the $# parameter is error-checking. To see what I mean, run the position_demo.sh script again, but only enter one name as an argument. You should see something like this:
[donnie@fedora ~]$ ./position_demo.sh VickyI have a cat, whose name is Vicky.I have another cat, whose name is .I have yet another cat, whose name is .The script that I just ran is ./position_demo.sh[donnie@fedora ~]$As you see, it gave me no warning about the fact that I didn’t list the correct number of names. Let’s modify things a bit to take care of that. Create the position_demo_2.sh script, and make it look like this:
#!/bin/bash# position_demoif [[ $# -ne 3 ]]; then echo "This script requires three arguments." exit 1fiecho "I have a cat, whose name is $1."echo "I have another cat, whose name is $2."echo "I have yet another cat, whose name is $3."echoechoecho "The script that I just ran is $0"Run this script with all three names, and you’ll get the same output that you got with the first script. Then, run it again with only one name, and you should see this:
[donnie@fedora ~]$ vim position_demo_2.sh[donnie@fedora ~]$ ./position_demo_2.sh VickyYou entered 1 argument(s).This script requires two arguments.[donnie@fedora ~]$That looks much better.
To introduce our next trick, take a look at the output of the date command, without specifying any formatting options, like this:
[donnie@fedora ~]$ dateFri Oct 6 03:24:39 PM EDT 2023[donnie@fedora ~]$You see seven fields in the output, which are:
- Day of week
- Month
- Date
- Time
- AM or PM
- Timezone
- Year
Now, create the position_demo_3.sh script, which will treat each field of the date output as a positional parameter. Make it look like this:
#!/bin/bashset $(date)echo $*echo "Day, First Argument: $1"echo "Month, Second Argument: $2"echo "Date, Third Argument: $3"echo "Time, Fourth and Fifth Arguments: $4, $5"echo "Time Zone, Sixth Argument: $6"echo "Year, Seventh Argument: $7"echo "$2 $3, $7"On the second line, you see another use for the set command that you haven’t yet seen. The first time you saw set, it was with the -o option to set shell options. This time, I’m using it without any options and with $(date) as an argument. Here’s what the bash man page says about using set in this manner:
Without options, display the name and value of each shell variable in a format that can be reused as input for setting or resetting the currently-set variables.
In this case, set is taking the output of $(date) and formatting it in a way that allows the individual fields to be used as positional parameters.
On the third line, you see where the real magic happens. The (date) on a single line. The rest of the echo commands just output a text string, followed by the value of the specified field or fields. Here’s what it looks like:
[donnie@fedora ~]$ ./position_demo_3.shFri Oct 6 03:46:28 PM EDT 2023Day, First Argument: FriMonth, Second Argument: OctDate, Third Argument: 6Time, Fourth and Fifth Arguments: 03:46:28, PMTime Zone, Sixth Argument: EDTYear, Seventh Argument: 2023Oct 6, 2023[donnie@fedora ~]$It works as it should, and looks pretty cool. Add this to the list of tricks to try at your next party.
I think that that about covers it for positional parameters. Let’s now look at exit codes.
Understanding Exit Codes
Section titled “Understanding Exit Codes”You’ve already seen some examples of using the exit command, which can either terminate a script normally or cause it to terminate early upon an error condition. What I haven’t explained yet, is about exit codes. There are two general classes of exit codes, which are:
- Standard shell exit codes: Each shell has its own defined set of exit codes. (To keep things simple, I’ll just talk about bash exit codes in this chapter.)
- User-defined exit codes: You can also define your own exit codes for different purposes.
Let’s talk about standard exit codes first.
Standard Shell Exit Codes
Section titled “Standard Shell Exit Codes”When a program or script runs successfully, it returns an exit code of 0. Otherwise, the exit code will be a non-0 number from 1 to 255. To demonstrate, use find to search through the /etc/ directory for the passwd file, like so:
[donnie@fedora ~]$ find /etc -name passwdfind: '/etc/audit': Permission deniedfind: '/etc/cups/ssl': Permission denied.../etc/pam.d/passwdfind: '/etc/pki/rsyslog': Permission deniedfind: '/etc/polkit-1/localauthority': Permission deniedfind: '/etc/polkit-1/rules.d': Permission denied......find: '/etc/credstore.encrypted': Permission denied/etc/passwd[donnie@fedora ~]$You see that find found the file, but we also have a lot of Permission denied errors due to the fact that there are directories that I can’t enter with my normal user privileges. Now, verify the exit code, like this:
[donnie@fedora ~]$ echo $?1[donnie@fedora ~]$The ? is a special variable that returns the exit code for the previous command that was just run. In this case, the exit code is 1, which tells me that there was some kind of error condition. The specific error was that find couldn’t enter certain directories to perform its search. So, let’s try this again with sudo, like so:
[donnie@fedora ~]$ sudo find /etc -name passwd[sudo] password for donnie:/etc/pam.d/passwd/etc/passwd[donnie@fedora ~]$ echo $?0[donnie@fedora ~]$This time I get exit code 0, which means that there were no error conditions.
Most of the time, you’ll see either 0 or 1 as the exit code. The complete list of codes that you might see include the following:
- 1 General errors
- 2 Misuse of shell builtins
- 126 Cannot invoke requested command
- 127 Command not found
- 128 Invalid argument to exit
- 128+n Fatal error signal n
- 130 Script terminated by.Ctrl-c
It’s possible to demonstrate some of the other codes. Start by creating the exit .sh script, like so:
#!/bin/bashexit nRight away, you can see the error. The exit command requires a numerical argument, and won’t work with an alphabetical argument. But, we’re going to pretend that we don’t see the error, and try to run it anyway. Here’s what you’ll get:
[donnie@fedora ~]$ ./exit.sh./exit.sh: line 2: exit: n: numeric argument required[donnie@fedora ~]$ echo $?2[donnie@fedora ~]$The 2 exit code indicates that I misused a shell builtin.
A shell builtin is just a command that doesn’t have its own executable program file, because it’s built into the bash executable program file. One would think that I would get a 128 code, since I provided an invalid argument to exit, but that’s not how it works. (In fact, I’m really not sure what I would have to do to get a 128 code. But, that’s okay.) To see the complete list of shell builtins, just view the builtins man page.
A 126 code normally means that you don’t have permission to run a command. For example, let’s say that I forgot to set the executable permission on a script, as you see here:
[donnie@fedora ~]$ ls -l somescript.sh<!-- page: 232 (printed 221) -->-rw-r--r--. 1 donnie donnie 0 Oct 7 16:26 somescript.sh[donnie@fedora ~]$Watch what happens when I try to run this script:
[donnie@fedora ~]$ ./somescript.shbash: ./somescript.sh: Permission denied[donnie@fedora ~]$ echo $?126[donnie@fedora ~]$You can generate a 127 code by trying to execute a command that doesn’t exist, like this:
[donnie@fedora ~]$ donniebash: donnie: command not found[donnie@fedora ~]$ echo $?127[donnie@fedora ~]$Obviously, my name is not a command.
The 128+n code means that some sort of fatal error condition occurred. The n signifies another digit that’s added to 128. For example, if you start a command and Ctrl-c out of it before it completes, you’ll get a code of 128+2, which equals 130. (The 2 in this case indicates the specific fatal condition.)
You can use standard exit codes within a shell script to make it handle different conditions. To see that, create the netchk.sh script, as follows:
#!/bin/bashif [[ $# -eq 0 ]]; then site="google.com"else site="$1"fiping -c 2 $site > /dev/nullif [[ $? != 0 ]]; then echo $(date +%F) ... Network Failure! logger "Could not reach $site."else echo $(date +%F) ... Success! logger "$site is reachable."fiThis script expects you to invoke it with a hostname, domain name, or an IP address as an argument. In the first if..then construct at the top, you see that if you don’t enter an argument, the script will default to using google.com as the argument.
Otherwise, it will use the argument that you specified. It will then try to ping the specified site. If the ping is successful, the exit code will be 0. Otherwise, it will be something other than 0.
In the second if…then construct, you see that if the exit code is not 0, it will echo a Network Failure message and send an entry to the system log file, which on the Fedora machine is /var/log/messages. Otherwise, it will echo a Success message. Here’s how that looks:
[donnie@fedora ~]$ ./netchk.sh2023-10-07 . . . Success![donnie@fedora ~]$ ./netchk.sh www.donnie.comping: www.donnie.com: Name or service not known2023-10-07 . . . Network Failure![donnie@fedora ~]$There’s not much else to say about the standard exit codes. So, let’s say a few words about user-defined exit codes.
User-defined Exit Codes
You can specify your own exit codes simply by specifying a numerical argument for exit. This is handy for whenever you might need to pass some specific exit code to an external program. The Nagios network monitoring tool is a great example.
Nagios is a tool that can monitor pretty much every type of device on your network. It can monitor various types of servers, workstations, routers, switches, and even printers. What makes it so cool is that it’s modular, which means that it works with plug-ins. If you need to monitor a particular device and find that there’s no plug-in that will do the job, you can just write your own. You can write plug-ins in a variety of programming languages, which includes shell scripting.
You can install a Nagios monitoring agent on a server or workstation that you want to monitor, and create a shell script that generates exit codes that Nagios expects to see. To understand how it works, check out this code snippet from a larger script:
#!/bin/bashos=$(uname)quantity=$(cut -f3 -d: /etc/passwd | grep -w 0 | wc -l)if [ $os == Linux ]; then if [ $quantity -gt 1 ]; then echo "CRITICAL. There are $quantity accounts with UID 0." exit 2 else echo "OKAY. There is only one account with UID 0." exit 1 fifiThis script is looking at the /etc/passwd file to see if there is more than one user with a UID of 0. That’s important, because UID 0 is what gives a user account root user powers. So, on any Linux system, you never want to see more than one user account with UID 0. In the if . . then construct, you see that if the script finds more than one UID 0 account, it will generate an exit code of 2. Otherwise, it will generate an exit code of 1.
This exit code and its corresponding echo command get passed to the Nagios monitoring agent. The monitoring agent will then pass the output from the echo command to the Nagios server, which will display the message on the Nagios dashboard. (You’ll see the entire script in just a few moments, when you get to the Looking at Some Real-World Examples section.)
That’s about it for exit codes. Let’s now take a closer look at echo.
More Information About echo
Section titled “More Information About echo”You’ve already seen the most simple way to use echo, which is to either display a message on the screen or send text into a text file. What you haven’t seen yet is echo’s various formatting options.
If you use it with the -n switch, you’ll prevent it from creating a new line at the end of the text output, like this:
[donnie@fedora ~]$ echo -n "The fat cat jumped over the skinny dog."The fat cat jumped over the skinny dog.[donnie@fedora ~]$Use it with the -e switch, and you’ll be able to use some backslash options. For example, to insert a vertical tab into a line of text, use the -e switch with the \v option, like this:
[donnie@fedora ~]$ echo -e "The fat cat jumped\v over the skinny dog."The fat cat jumpedover the skinny dog.[donnie@fedora ~]$To insert a horizontal tab, use the \t option, like this:
[donnie@fedora ~]$ echo -e "The fat cat jumped\t over the skinny dog."The fat cat jumped over the skinny dog.[donnie@fedora ~]$If you want to insert a backslash into the text, just use two consecutive backslashes, like this:
[donnie@fedora ~]$ echo -e "The fat cat jumped over the thin\\skinny dog."The fat cat jumped over the thin\skinny dog.[donnie@fedora ~]$You’re not limited to just echoing text messages. You can also use a wildcard character to show a list of files that you have in the current directory, like this:
[donnie@fedora ~]$ echo *<!-- page: 235 (printed 224) -->1 15827_zip.zip 18.csv 2023-08-01_15-23-31.mp4 2023-08-01_16-26-12.mp4 2023-08-02_13-57-37.mp4 2023-10-25_price.txt 21261.zip 4-2_Building_an_Alpine_Container.bak 4-2_Building_an_Alpine_Container.pptx 46523.zip 48986.zip 50645.zip 54586.zip 70604.zip access_log_parse.sh access_log_parse.txt actorfile_10.txt actorfile_11.txt actorfile_1.txt actorfile_2.txt actorfile_4.txt actorfile_5.txt actorfile_6.txt actorfile_7.txt actorfile_8.txt actorfile_9.txt add_fields.awk add-repos.sh addresses.txt alignment_1.txt alignment_2.txt alma9_default.txt alma9_future.txt alma_link.txt...[donnie@fedora ~]$You can also echo a message along with the file list, like so:
[donnie@fedora ~]$ echo -e "These are my files:\n" *These are my files:15827_zip.zip 2023-08-01_15-23-31.mp4 2023-08-01_16-26-12.mp4...test.txt yad-form.sh zoneinfo.zip[donnie@fedora ~]$With a bit of imagination, you’ll be able to use these echo formatting options to enhance the appearance of your screen output and text documents.
Sadly, as cool as these formatting options for echo are, they don’t work well on certain non-bash shells, such as dash. In Chapter 19—Shell Script Portability, I’ll show you how to fix that by using printf instead of echo.
That’s about it for echo. Let’s move on to the real world.
Looking at Some Real-World Examples
Section titled “Looking at Some Real-World Examples”In this section, I’ll show you some practical, real-life things that you can do with some of the techniques that we’ve covered so far. Actually, rather than just showing you, I’ll let you get your hands dirty with some cool hands-on labs.
Hands-on Lab: Using if..then
Section titled “Hands-on Lab: Using if..then”This is absolutely a real-life example. Several years ago, I created this script as a plug-in for the Nagios network monitoring system. The scenario was that we wanted to make sure that malicious hackers haven’t added a rogue UID 0 account to the /etc/passwd file on Linux and FreeBSD machines. That’s because any account with a UID setting of 0 in the passwd file has full root privileges, and we don’t want any unauthorized accounts to have root privileges.
The problem is that on Linux machines there’s only supposed to be one user account with UID 0, and on FreeBSD there are two accounts with UID 0. (One UID 0 account is named toor, which has bash set as the default shell. The other UID 0 account is root, which has csh set as the default shell.) So, we needed a script that will work on both operating systems. (Note that you’ll be altering the passwd file for this lab, so you’ll want to do this on a virtual machine, and not on a real production machine.)
Note that the exit 1 and exit 2 status codes that you’ll see are what Nagios expects to see to indicate either OKAY or CRITICAL. Also note that you can add more elif stanzas if you want to check other UNIX or UNIX-like operating systems. (In fact, you’ll see that I’ve just now added code to check macOS and OpenIndiana.) With the introduction out of the way, let’s get to the procedure.
-
Unfortunately, the script is too long to reproduce in the book. So, go to the Github repository and download the UID-0_check.sh script. Transfer it to a Linux virtual machine. Open the script in your text editor, and examine the code.
-
Run the script to see the results. You should see this message:
[donnie@fedora ~]$ ./UID-0_check.shOKAY. There is only one account with UID 0.[donnie@fedora ~]$- WARNING: Again I say, do this on a virtual machine, not on your production workstation.
On a Linux virtual machine, create another user account, using the appropriate user-creation command for your Linux distro. Open the /etc/passwd file in your text editor, and change the UID number for the new user to 0.
This UID field is the third field in each line of the passwd file. For example, you see here that Vicky’s UID is 1001:
vicky:x:1001:1001::/home/vicky:/bin/bashChanging her UID to 0 will make the line look like this:
vicky:x:0:1001::/home/vicky:/bin/bash- Save the file and run the script again. You should now see a message that looks like this:
[donnie@fedora ~]$ ./UID-0_check.shCRITICAL. There are 2 accounts with UID 0.[donnie@fedora ~]$-
Delete the new user account.
-
Create a FreeBSD virtual machine and install sudo and bash as I showed you in the Preface chapter. Transfer the UID-0_check.sh script to it, and repeat Steps 3 through 5. This time, you should see that 2 accounts are OKAY, and that 3 accounts are CRITICAL. This will give you a chance to see how the elif [ $os == FreeBSD ]; then stanza at the bottom of the script can correctly detect which operating system you’re running, so that it can run the correct code.
End of lab
Hands-on Lab — Parsing an Apache Access Log
In this lab, I’ll show you how much power a one-command shell script can have. Building up that one command can be a bit tricky though, so I’ll show you how to build it one step at a time, ensuring that each step works properly before continuing to the next step. If you’re ready, let’s dig in.
-
Set up a Fedora Server virtual machine with Bridged networking. (You’ll need Bridged networking so that you can access the machine from other machines on your network.)
-
Install and activate the Apache webserver, like this:
sudo dnf install httpdsudo systemctl enable --now httpd -
Open Port 80 on the virtual machine’s firewall, like this:
sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --reload -
From as many other machines on your network as possible, open a web browser and navigate to the virtual machine’s IP address. The URL that you enter should look something like this:
http://192.168.0.10Note that you can access this from either physical machines or other virtual machines that are on the same network. Also, note that there’s no need to set up your own web page, because the default Fedora Webserver Test Page will work fine for your needs.
-
View the Apache access log, like this:
sudo less /var/log/httpd/access_logNote how each line begins with the IP address of each machine that accessed this website. Here’s an example:
192.168.0.25 - - [06/Oct/2023:16:44:15 -0400] "GET /poweredby.pngHTTP/1.1" 200 5714 "http://192.168.0.10/" "Mozilla/5.0 (Windows NT 10.0;Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0" -
You see that the source IP address is in the first field, and that the fields are separated by blank spaces. So, one way that we can see just the list of source IP addresses is to use cut, and to specify a blank space as the delimiter to view just the first field. The command and its output would look something like this:
[donnie@fedora-server ~]$ sudo cut -d " " -f1 /var/log/httpd/access_log::1192.168.0.16192.168.0.16192.168.0.27...
With only one exception, you see the list of IPv4 addresses of the machines that accessed this server. The one exception is the IPv6 address at the top of the list, which is the localhost address of the Fedora Server machine. (You likely won’t see this IPv6 address, unless you access the page from within the virtual machine itself.)
- So far, so good. You’ve successfully isolated the first field. Let’s now add the second part, which will sort the output so that the uniq filter will work properly in the next step. Here’s what that looks like:
sudo cut -d" " -f1 /var/log/httpd/access_log | sortBy using sort without the -n option, the list doesn’t get sorted in proper numerical order. But for this step, that doesn’t matter.
- The next step is to eliminate duplicate IP addresses from the output, and to also count how many there are of each in the source file. Here’s how that looks:
[donnie@fedora-server ~]$ sudo cut -d" " -f1 /var/log/httpd/access_log | sort | uniq -c 1 ::1 11 192.168.0.16 4 192.168.0.25 4 192.168.0.27 4 192.168.0.8 1 192.168.0.9[donnie@fedora-server ~]$- We’ll now do a reverse numerical sort on the number of times that each IP address occurs, like so:
[donnie@fedora-server ~]$ sudo cut -d" " -f1 /var/log/httpd/access_log | sort | uniq -c | sort -nr 11 192.168.0.16 4 192.168.0.8 4 192.168.0.27 4 192.168.0.25- Now that you know that the command works properly, create the ipaddress_count.sh script, and make it look like this:
#!/bin/bashcut -d" " -f1 /var/log/httpd/access_log | sort | uniq -c | sort -nrBe aware that you’ll need to use sudo to run this script.
- Finally, let’s fancy things up a bit. Add some code to save the results to a text file with a time-stamp in its filename. It should look like this:
#!/bin/bashtimestamp=$(date +%F)echo "These addresses have accessed this webserver as of $timestamp." > ipaddress_list_$timestamp.txtcut -d" " -f1 /var/log/httpd/access_log | sort | uniq -c | sort -nr >> ipaddress_list_$timestamp.txtOf course, there are other available programs that do a more comprehensive job of parsing your webserver log files. But, this script is handy for a quick analysis of who is accessing your server.
End of lab
Let’s move on to the final lab.
Hands-on Lab – Beta Testing a Hard Drive
The final example involves an experience that I had quite a few years ago. That’s when the good folk at Western Digital invited me to participate in a beta test of a new model hard drive. All I really had to do was to keep the drive running for the whole four-month test period, and then collect log data from the drive’s BIOS at the end of the test period. But, I went a bit beyond that by writing a shell script that automatically collected drive performance data on a daily basis. As before, do this on your Fedora Server virtual machine.
- To collect drive performance data, you’ll need to install a couple of packages, like this:
sudo dnf install sysstat smartmontools- Start the sysstat service and ensure that it’s active, like this:
sudo systemctl start sysstatsystemctl status sysstat- You’ll use the sar component of the sysstat package to collect your data. But, it will be a few minutes before any sar data become available. While you’re waiting, generate some hard drive activity by doing a system update, like so:
sudo dnf -y upgrade- View the sar man page and take note of the different types of data that can be collected with the various sar option switches. You’ll be seeing several of those options in the shell script.
This is another one of those scripts that’s too large to reproduce in the book. So, download the hard_drive.sh script from the Github repository. Open it in your text editor and study it. I’ve covered all of the concepts that I’ve used in this script, so you should be able to figure out what it’s doing.
- The last command in the script is a smartctl command, which requires sudo privileges. So, you’ll need to use sudo to run the script, like so:
sudo ./hard_drive.shBe patient, because this takes a few minutes to run. Also, be aware that the virtual drive of your virtual machine isn’t smartmontools-aware, which means that you’ll see some warning messages in your report.
-
When the script has finished running, look at the generated report in the Drive_Reports directory.
-
Feel free to run this script on your Linux host machine. It should run on most any Linux distro, as long as you have the sysstat and smartmontools packages installed, and the sysstat service is running.
End of Lab
All right, that wraps it up for this chapter. Let’s summarize and move on.
Summary
Section titled “Summary”We covered an incredible amount of ground in this chapter, and I hope that I haven’t overwhelmed you. What I wanted to do was to provide you with a comprehensive overview of the concepts and techniques that you would use to build a usable shell script. We started with some techniques that are unique to shell scripting, and followed up with techniques that are common to most all programming languages.
And really, that’s one of the coolest things about learning shell scripting. It’s much easier to learn than higher-level languages such as C, Java, or Rust, but it’s still extremely useful. And, as you learn shell scripting, you also learn about the constructs and concepts that also apply to the higher-level languages. So, if you ever plan to learn another programming language, learning shell scripting first can help you prepare for it.
But, even with all that we’ve covered, we’re not done yet. In the next chapter, I’ll present a few more ways to filter and manipulate text. I’ll see you there.
Questions
Section titled “Questions”-
Which of the following snippets represents the most preferred way to perform command substitution?
a.
`command`b.
%(command)c.
"command"d.
$(command) -
You need to create an array of names. How would you do that?
a.
set array=namesnames=( Vicky Frank Cleopatra Katelyn )b.
array=namesnames=( Vicky Frank Cleopatra Katelyn )c.
array namesnames=( Vicky Frank Cleopatra Katelyn )d.
declare namesnames=( Vicky Frank Cleopatra Katelyn )e.
declare -a namesnames=( Vicky Frank Cleopatra Katelyn ) -
How would you view the exit code of a command that you just ran?
a.
echo $#b.
echo $?c.
echo $$d.
echo $! -
You want to create a loop that will read a list of names, and then echo the names into another text file. But, you want to skip two of the names. Which of the following commands would make your script do that?
a.
breakb.
skipc.
continued.
stop
-
You want to compare two numerical values to see if they’re equal. which of the following operators would you use?
a. = b. -eq c. == d. -ne
Further Reading
- What is the Bash Shebang and How to Use It: https://www.rosehosting.com/blog/what-is-the-bash-shebang/
- An Introduction to Parameter Expansion in bash: https://opensource.com/article/17/6/bash-parameter-expansion
- Shell Parameter Expansion (Bash Reference Manual): https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
- Introduction to if: https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
- Bash while Loop: https://linuxize.com/post/bash-while-loop/
- How to Find Most Used Disk Space Directories and Files in Linux: https://www.tecmint.com/find-top-large-directories-and-files-sizes-in-linux/
- Standard Exit Status Codes in Linux: https://www.baeldung.com/linux/status-codes
- How to Use the sar Command on Linux: https://www.howtogeek.com/793513/how-to-use-the-sar-command-on-linux/
Answers
- d
- e
- b
- c
- b