Boosting Your Command-line Efficiency
local graph
Chapter 6 — Boosting Your Command-line Efficiency
Section titled “Chapter 6 — Boosting Your Command-line Efficiency”Throughout this book, we’ve been using the command line quite heavily. Using the shell, we’ve installed packages, created users, edited configuration files, and more. In the last chapter, we took a look at file management to enhance our terminal skills further. This time around, we’ll dedicate an entire chapter to the shell, with the goal of becoming more efficient with it. Here, we’ll take what we already know and add some useful time-saving tips, some information on looping, variables, and we’ll even look into writing scripts.
In this chapter, we will cover the following topics:
- Understanding the Linux shell
- Understanding Bash history
- Learning some useful command-line tricks
- Understanding variables
- Writing simple scripts
- Putting it all together: Writing an
rsyncbackup script
Let’s begin this chapter with further discussion regarding the Linux shell, which will help us better understand how we’re interacting with the server while we enter commands.
Understanding the Linux shell
Section titled “Understanding the Linux shell”When it comes to the Linux shell, it’s important to understand what exactly the term pertains to. We’ve been using the command line repeatedly throughout the book, but we haven’t yet had any formal discussion about the actual interface through which our commands are entered.
Essentially, we’ve been entering our commands into a command interpreter known as the Bourne Again Shell, or simply Bash. Bash is just one of many different shells that you can use to enter commands.
There are other options, including Zsh, Fish, and ksh, but Bash is the default command shell for the majority of Linux distributions. It’s even available on macOS (although the default on that platform is Zsh nowadays), as well as on Windows by installing the Windows Subsystem for Linux. Therefore, by understanding the basics of Bash, your knowledge will be compatible with other distributions and platforms. While it’s fun to learn other shells such as Zsh, Bash is definitely the one to focus the most attention on if you’re just starting.
You may wonder, then, where you configure the shell that your user account will use. If you recall from Chapter 2, Managing Users and Permissions, we looked at the /etc/passwd file. As I’m sure you remember, this file keeps a list of user accounts available on the system. Go ahead and take a look at this file to refresh yourself by entering the following command:
cat /etc/passwdThis will produce an output like the one shown in Figure 6.1:

Text Description automatically generated
Figure 6.1: The last several lines of a sample /etc/passwd file
See the last field in every entry? That’s where we configure which shell is launched when a user logs in or starts a new terminal session. Unless you’ve already changed it, the entry for your user account should read /bin/bash.
You’ll see other variations in this file, such as /bin/false or /usr/sbin/nologin. These are actually invalid shells that will prevent a user from logging in to the system if one of these is set as the default for that user. While it may seem strange to set a user’s shell to one that prevents them from logging in, this practice is fairly common – not all user accounts need to log in to a server.
System accounts also exist alongside normal user accounts, which are created for background jobs. These system users won’t need to actually log in to the system in order to do their work, so it’s common to take that a step further and set the shell of a system user to an invalid shell, so that way, the account cannot be used to log in to the server if it’s taken over by an outside threat actor (the less an account can do, the safer it is).
The shell program itself is responsible for reading the commands you type and having the Linux kernel execute them. Some shells, Bash notably, have additional features, such as history, that are very useful to administrators.
Understanding Bash history
Section titled “Understanding Bash history”Speaking of history, let’s dive right into that concept. By default, Bash keeps track of all the commands you enter during your sessions, so that if you need to recall a previously entered command, you can definitely do so. History also serves another purpose, and that is seeing what other users have been up to. However, since users can edit their own history to cover their tracks, it’s not always useful for that purpose.
You may have already seen Bash’s history feature in some form, if you’ve ever pressed the up and down arrows on the shell to recall a previously used command. If you didn’t already know you could do that, go ahead and give it a try. You should see that by pressing the up and down arrows, you can cycle through commands that you’ve used previously.
Another trick is that you can also simply type history in the shell and see a list of previously entered commands, as shown in Figure 6.2:

A screenshot of a computer Description automatically generated with medium confidence
Figure 6.2: Output from the history command
At this point, you can copy and paste a command you’ve used previously from this list to run it again. In fact, there’s an even easier way. Do you notice the number on the left of each command? We can utilize that number to quickly recall a previously used command. In my screenshot, item 566 is where I ran sudo apt update. If I wanted to run that same command again, I could simply enter the following command:
!566In this case, I typed just four characters, and I was able to recall the previously used command, which performs the same action as typing this:
sudo apt updateThat saves a lot of typing, which is great because we administrators want to type as little as possible (unless we’re writing a book).
Let’s look at a few additional history commands we can use. First, if we want to delete something from the history, we can simply do this:
history -d 566In this example, we deleted item 563 from Bash’s history. To delete a different history entry, simply replace 563 with whatever the number is for the item we would want to remove. You may be wondering why deleting something from the history would be necessary. The answer to that is simple: sometimes we make mistakes. Perhaps we mistyped something, and we don’t want a junior administrator to look at the history and rerun an invalid command. Worse, if we accidentally saved a password to the history, it would be there for all to see. We would definitely want to remove that item so that the password isn’t saved in plain text in the history file. One very common example of this is with MySQL or MariaDB. When you enter the MySQL or MariaDB shell, you can use the -p option and type the password in one line. It would look something like this:
mariadb -u root -pSuperSecretPasswordThat command may appear useful, because in one command you’d be logged in to your database server as its own version of the root user. However, this is one of my pet peeves—I really don’t like it when people run commands that include a password in the clear. Having the root password in your shell’s history is a HUGE security risk. This is just one example of something you won’t want in our Bash history, though. My main goal here is to demonstrate that you should think about security when entering commands. If you have a potentially sensitive item in your command history, you should remove it. In fact, you can actually enter a command and not have it saved in the history at all. Simply prefix the command with a space. If you do, it will not be recorded in the history file. Go ahead, give it a try and see for yourself.
Having commands prefixed with a space ignored in Bash is actually a custom option enabled by default in Ubuntu Server. Not all distributions include this feature enabled by default. If you’re using a distribution that doesn’t have this enabled already, add the following to your .bashrc file (we will talk about this file in greater detail later).
HISTCONTROL=ignorebothThis configuration line also causes duplicate commands to not be entered into the history file as well, which can condense the history file.
So, you might be wondering, where is this history information actually stored? Check out the .bash_history file, which is found in your home directory (or /root for the root user). When you exit your shell, your history is copied to that file. If you remove that file, you’re effectively clearing your history. I don’t recommend you make a habit of that, though. Having a history of commands is very useful, especially when you may not remember how you solved a problem last time. History in Bash can save you from looking up a command again. To find out more about what the history command can do, check out the relevant man page with man history.
Learning new tricks with the command line that allow me to work more efficiently is a great feeling, at least for me. In the next section, we’ll explore some useful tricks we can utilize while working with the shell.
Learning some useful command-line tricks
Section titled “Learning some useful command-line tricks”Productivity hacks utilizing the shell are some of my favorite things in this world, right up there with music, video games, and Diet Pepsi. There’s nothing like the feeling you get when you discover a useful feature that saves you time or increases your efficiency. There are many things I’ve discovered along the way that I wish I had known earlier on. One of my goals while writing this book is to teach you as many things as I can that took me longer to learn than I’m comfortable admitting to. In this section, in no particular order, I’ll go over a few tricks that increased my workflow.
First, entering !! (two exclamation marks) in your terminal will repeat the command you last used. By itself, this may not seem like much. After all, you can press the up arrow key once and press Enter to recall the previous command and execute it. But, when paired with sudo, !! becomes more interesting. Imagine for a moment that you entered a command that needs root privileges, but you forgot to use sudo. We’ve all made this mistake. In fact, as of the time I’m writing this chapter, I’ve been using Linux for 20 years and I still forget to use sudo from time to time. When we forget sudo, we have to type the command all over again. Or, we can just do this:
sudo !!And just like that, you prefixed the previously used command with sudo without having to completely retype it.
Speaking of avoiding unnecessary typing, a very easy (yet incredibly useful) feature is Tab Completion. Often, the Bash shell will be able to automatically complete part of your commands. If you start typing a few characters of a command or path, press Tab on your keyboard, and if the characters you’ve typed are enough to narrow down the result, the shell will complete the path for you. You can also press Tab twice in succession to see a list of possibilities that match the characters you’ve typed so far. Go ahead and give it a shot. By way of a quick example, you can type ls along with the path to your home directory, leaving some characters out on purpose. Then press Tab, and see whether the command automatically completes. For example, I can type the following into the terminal:
ls /home/jAnd after I press Tab, it completes the command for me:
ls /home/jayIn addition, there are other special keyboard keys that will help you to navigate the command line quicker. Here’s a table containing some of the most useful keyboard shortcuts:
| Keyboard shortcut | Result |
|---|---|
| Ctrl + a | Moves the cursor to the beginning of the line |
| Ctrl + e | Moves the cursor to the end of the line |
| Ctrl + l | Clears the screen |
| Ctrl + k | Deletes characters from the cursor to the end of the line |
| Ctrl + u | Deletes everything you’ve typed on that line (also works to clear text while entering a password) |
| Ctrl + w | Deletes the word to the left of the cursor |
Going a bit further into the command history, we can also press Ctrl + r on the shell to initiate a search. After pressing these keys, we can start typing a command, and we’ll get a preview of a command that matches what we’re typing, which will be narrowed down further as we type more characters of it. This is one of those things that is hard for me to describe, and screenshots certainly don’t help here, so go ahead and just give it a shot. For example, press Ctrl + r and then start typing sudo apt. The last time you used that command should appear, and you can press Ctrl + r again, and again, and again to see additional examples of commands that you’ve typed in the past that contain those characters. When you get efficient with this, it’s actually faster than the history command, but it takes a bit to get used to this.
Another fun trick is editing a command you’ve previously typed in a text editor. I know this sounds strange, but hear me out. Assume you pressed the up arrow, you have a very long command, and you just want to edit part of it without having to execute the entire thing, perhaps a command like this:
sudo apt update && sudo apt install apache2Let’s assume you want to install nginx instead of apache2, but the rest of the command is right. If you hold Ctrl and then press x followed by e, the command will open in a text editor. There, you can change the command. Once you’re done making your changes, the command will execute once you save the file. Admittedly, this is usually only useful when you have a very long command and you need to just change part of it. It’s also a little weird, but so are computers.
Did you notice the two & symbols in the previous command? This is another useful trick; you can actually chain commands together. In the previous example command, we’re telling the shell to execute sudo apt update. Next, we’re telling the shell to then execute sudo apt install apache2. The double ampersand is known as the logical AND operator, so the second command is run if the first was successful. If the first command was successful, the second command will execute right after. Another method to chain commands is this:
sudo apt update; sudo apt install apache2The difference with the semicolon is that we’re telling the shell to execute the second command regardless of whether the first command was successful. You may then be wondering, what constitutes success on the shell? An obvious answer to this question might be “it’s successful if there are no error messages.” While that’s often true, the shell utilizes exit codes to programmatically attribute success or failure. You can see the exit code of a command by typing this immediately after the previous command finishes:
echo $?An exit code of 0 means success; anything else is some sort of error. Different programs will attribute different codes to different types of failures, but 0 is always a success. With this command, what we’re actually doing is printing the content of a variable. $? is actually a variable, which in this case only exists to hold an exit code. The echo command itself can be used to print text to the shell, but it’s often used to print the contents of a variable (we’ll get into this in more detail in the Understanding variables section).
Now, it’s time for my favorite time-saving trick of them all—command aliases. The concept of an alias is simple: it allows you to create a command that is just another name for another command. This allows you to simplify commands down to just one word or a few letters. Consider this command, for example:
alias install="sudo apt install"When you enter the previous command, you will receive no actual output. But what happens is now you have a new command available— install. This command isn’t normally available; you just created it with this command.
You can verify that the alias was created successfully by simply running the alias command, which will show you a list of aliases present in the shell. If you create a new alias, you should see it in the output. You’ll also see additional aliases in the output that you did not create. This is because Ubuntu sets up some by default. In fact, even the ls command is an alias!
With this new alias created, any time you execute install on the command line, you’re instead executing sudo apt install. Now, installing packages becomes simpler:
install tmuxJust like that, you installed tmux. You didn’t have to type sudo apt install tmux; you just simplified the first three words in the command into install. In fact, you can simplify it even further:
alias i='sudo apt install'Now, you can install a package with this:
i tmuxWith aliases, you can get very creative. Here are some of my personal favorites.
View the top 10 most-CPU-consuming processes:
alias cpu10='ps -L aux | sort -nr -k 3 | head -10'View the top 10 most-RAM-consuming processes:
alias mem10='ps -L aux | sort -nr -k 4 | head -10'View all mounted filesystems, and present the information in a clean tabbed layout:
alias lsmount='mount | column -t'Clear the screen by simply typing c:
alias c=clearWhat other aliases can you come up with? Think of a command you may use on a regular basis and simplify it.
There’s one issue though, and that is the fact that when you exit your terminal window, your aliases are wiped out. How do you retain them? That leads me to my next productivity trick, editing your .bashrc file. This file is present in your home directory and is read every time you start a new terminal session. You can add all of your alias commands there; just add them somewhere in the file (for example, at the end). You will need to include the entire command, beginning with alias and ending with the commands in quotes. If you wanted to steal my example aliases, you would enter the following lines somewhere in your .bashrc file:
alias i='sudo apt install'alias cpu10='ps -L aux | sort -nr -k 3 | head -10'alias mem10='ps -L aux | sort -nr -k 4 | head -10'alias lsmount='mount |column -t'There are, of course, additional time-saving tricks that we could talk about here, but then again, Bash is so complex that we can write an entire book about it (and many people have). As we go along in this chapter, I’ll give you even more tips. For now, here’s a final trick, which changes your working directory back to the previous directory you were in:
cd -That simple command was mentioned in Chapter 4, Navigating and Essential Commands, but it’s worth a second mention—you’re welcome! Next, let’s take a look at shell variables, which allow us to store information for easy access in other commands.
Understanding variables
Section titled “Understanding variables”Bash is more than just a shell. You could argue that it is very similar to a complete programming language, and you wouldn’t be wrong. Bash has a built-in scripting engine (we will get into scripting later) and there are many debates as to what distinguishes a scripting language from a programming language, and that line becomes more and more blurred as new languages come out.
As with any scripting language, Bash supports variables. The concept of variables is very simple in Bash, but I figured I’d give it its own (relatively short) section to make sure you understand the basics. You can set a variable with a command such as the following:
myvar='Hello world!'When Bash encounters an equal sign after a string, it assumes you’re creating a variable. Here, we’re creating a variable named myvar and setting it equal to Hello world! Whenever we refer to a variable, though, we need to specifically clarify to Bash that we’re requesting a variable, and we do that by prefixing it with a dollar symbol ($). Consider this command:
echo $myvarIf you’ve set the variable as I have, executing that command will print Hello world! to stdout. The echo command is very useful for printing the contents of variables. The key thing to remember here is that when you set a variable, you don’t include the $ symbol, but you do when you retrieve it. Also, keep in mind that there’s no space on either side of the equals sign.
You will see variations of variable name formats as you work with various Linux servers. For example, you may see variable names in all caps, camel case (MyVar), as well as other variations. These variations are all valid, and depending on the background of the individual creating them (developers, administrators, and so on), you may see different forms of variable naming. It’s also extremely common that built-in variables created as part of the distribution will be named in all upper case.
Variables work in other aspects of the shell as well, not just with echo. Consider this:
mydir="/etc"ls $mydirHere, we’re storing a directory name in a variable and using the ls command against it to list its contents. This may seem relatively useless, but when you’re scripting, this will save you time. Anytime you need to refer to something more than once, it should be in a variable. That way, in a script, you can change the contents of that variable just one time and everywhere in the script will reference it.
There are also variables that are automatically present in your shell that you did not explicitly set yourself. Enter this command for fun:
envWow! You should see a lot of variables, especially if you enter it in a desktop version of Ubuntu.
These variables are set by the system, but can still be accessed via echo as you would any other. Some notable ones include $SHELL (stores the name of the binary that currently handles your shell), $USER (stores your current username), and $HOST (stores the hostname for your device). Any of these variables can be accessed at any time, and may even prove beneficial in scripts.
We’ve already gone over standard output (stdout), standard error (stderr), and standard input (stdin) in the previous chapter. We’ll use standard input again here, when we capture input to store it as a variable. Try this command for example:
read ageWhen you run this command, you’ll just be brought to a blank line, with no indication as to what you should be doing. Go ahead and enter your age, and then press Enter. Next, run this:
echo $ageIn a script, you would want to inform the user what they should be entering, so you would probably use something similar to these commands:
echo "Please enter your age"read ageecho "Your age is $age"We’ve discussed standard input in the previous chapter, and we can see it in action again here as we capture input from the user and store it in a variable.
Automation is a subject we’ll explore multiple times throughout the remainder of the book, which will include more advanced subjects such as configuration management. Writing scripts is the simplest form of automation, which gives you the ability to type commands in a text file and have them all execute. That’s what we’ll explore next.
Writing simple scripts
Section titled “Writing simple scripts”This is the section where everything we’ve talked about so far starts to come together. Writing scripts can be very fun and rewarding, as they allow you to automate large jobs or just simplify something that you find yourself doing over and over. The most important point about scripting is this: if it’s something you’ll be doing more than once, you really should be making it into a script. This is a great habit to get into.
A script is a very simple concept; it’s just a text file that contains commands for your shell to execute one by one. A script written to be executed by Bash is known as a Bash script, and that’s what we’ll work on creating in this section.
At this point, I’m assuming that you’ve practiced a bit with a text editor in Linux. It doesn’t matter if you use Vim or Nano. Since we’ve edited text files before (we went over that in Chapter 5, Managing Files and Directories), I’m under the assumption that you already know how to create and edit files. We’ll be using a text editor to create a simple script as an example, using the following command:
nano ~/myscript.shIf you weren’t already aware, a tilde (~) is just a shortcut for a user’s home directory. Therefore, on my system, the previous command would be the same as if I had typed:
nano /home/jay/myscript.shInside the file, type the following:
#!/bin/bashecho "My name is $USER"echo "My home directory is $HOME"Save the file and exit the editor. In order to run this file as a script, we need to mark it as executable:
chmod +x ~/myscript.shTo execute it, we simply call the path to the file and the filename:
~/myscript.shThe output should look similar to the following:
My name is jayMy home directory is /home/jayThe first line, #!/bin/bash, might seem strange if you haven’t seen it before. Normally, lines starting with a hash symbol (#) are ignored by the interpreter. The one on the first line is an exception to this. The #!/bin/bash entry we see on the first line is known as a hash bang, or shebang. Basically, it just tells the kernel which interpreter to use in order to run the commands inside the script. There are other interpreters we could be using, such as #!/usr/bin/python if we were writing a script in the Python language. Since we’re writing a Bash script, we used #!/bin/bash.
The lines that followed were simple print statements. Each one used a system variable, so you didn’t have to declare any of those variables as they already existed. Here, we printed the current user’s username and home directory.
The concept of scripting becomes more valuable when you start to think of things you do on a regular basis that you can instead automate. To be an effective Linux administrator, it’s important to adopt the automation mindset. Again, if you are going to do a job more than once, script it. Here’s another example script to help drive this concept home. This time, the script will actually be somewhat useful:
#!/bin/bashsudo apt install -y apache2sudo apt install -y libapache2-mod-php8.1sudo a2enmod php8.1sudo systemctl restart apache2What we’ve done here is theoretically scripted the setup of a web server. We could extend this script further by having it copy site content to /var/www/html, enable a configuration file, and so on. But from the preceding script, you can probably see how scripting can be useful in condensing the amount of work you do. This script could be an advanced web server install script that you could simply copy to a new server and then run.
Notice that the example uses the -y option with apt. If you weren’t already aware, that automatically answers yes to prompts that may come up as part of the process. Scripts are typically not interactive, meaning there may not be an administrator sitting in front of it to answer prompts when they appear. Also, using the a2enmod command to enable php8.1 was not really necessary, as it would’ve been enabled automatically as part of installing the libapache2-mod-php8.1 package. But I think you get the idea; we want to be explicit in scripts and type instructions for the exact state we want things to be in.
Now, let’s get a bit more advanced with scripting. The previous script only installed some packages, something we probably could’ve done just as easily by copying and pasting the commands into the shell. Let’s take this script a bit further. Let’s write a conditional statement. Here’s a modified version of the previous script:
#!/bin/bash# Install Apache if it's not already presentif [ ! -f /usr/sbin/apache2 ]; then sudo apt install -y apache2 sudo apt install -y libapache2-mod-php8.1 sudo a2enmod php8.1 sudo systemctl restart apache2fiNow it’s getting a bit more interesting. The first line after the hash bang is a comment, letting us know what the script does:
# Install Apache if it's not already presentComments are ignored by the interpreter, but are useful in letting us know what a block of code is doing.
Next, we start an if statement:
if [ ! -f /usr/sbin/apache2 ]; thenBash, like any scripting language, supports branching and the if statement is one way of doing that. Here, it’s checking for the existence of the apache2 binary. The -f option here specifies that we’re looking for a file. We can change this to -d to check for the existence of a directory instead. The exclamation mark is an inverse. It basically means we’re checking if something is not present. If we wanted to check if something is present, we would omit the exclamation mark. Basically, we’re setting up the script to do nothing if Apache is already installed. In this case, inside the brackets we are just executing a shell command, and then the result is checked. The commands sandwiched inside the if statement are simply installing packages.
Finally, we close out our if statement with the word if backward (fi). If you forget to do this, the script will fail.
With regard to the concept of if statements, we can compare values as well. Consider the following example:
#!/bin/bashmyvar=1if [ $myvar -eq 1]; then echo "The variable equals 1"fiWith this script, we’re merely checking the contents of a variable, and taking action if it equals a certain number. Notice we didn’t use quotation marks when creating the variable, since we just set a number (integer) here. We would’ve only used quotation marks if we wanted to set the variable value to a string. We can also take action if the if statement doesn’t match:
#!/bin/bashmyvar=10if [ $myvar -eq 1]; then echo "The variable equals 1"else echo "The variable doesn't equal 1"fiThis was a silly example, I know, but it works as far as illustrating how to create an if / else logic block in Bash. The if statement checks to see whether the variable was equal to 1. It isn’t, so the else block executes instead.
The -eq portion of the command is similar to == in most programming languages. It’s checking to see whether the value is equal to something. Alternatively, we can use -ne (not equal), -gt (greater than), -ge (greater than or equal to), -lt (less than), and so on.
At this point, I recommend you take a break from reading to further practice scripting (practice is key to committing concepts to memory). Try the following challenges:
- Ask the user to enter input, such as their age, and save it to a variable. If the user enters a number less than 30, tell them they’re young. If the number is equal to or greater than 30,
echoa statement telling them that they’re old. - Write a script that copies a file from one place to another. Make the script check to see whether that file exists first, and have an
elsestatement printing an error if the file doesn’t exist. - Think about any topic we’ve already worked on during this book, and attempt to automate it.
Now, let’s take a look at another concept, which is looping. The basic idea behind looping is simply doing something repeatedly until a condition has been met. Consider the following example script:
#!/bin/bashmyvar=1while [ $myvar -le 15 ]do echo $myvar ((myvar++))doneLet’s go through the script line by line to understand what it’s doing.
myvar=1With this new script, we’re creating a control variable, called myvar, and setting it equal to 1.
while [ $myvar -le 15 ]Next, we set up a while loop. A while loop will continue until a condition is met. Here, we’re telling it to execute the statements in the block over and over until $myvar becomes equal to 15. In fact, a while loop can continue forever if you enter something incorrectly, which is known as an infinite loop. An infinite loop is dangerous, and can cause your server to stop responding. If you used -ge 0 instead, you would’ve created exactly that.
doWith do, we’re telling the for loop to prepare itself to start doing something.
echo $myvarHere, we’re printing the current content of the $myvar variable—nothing surprising here.
((myvar++))With this statement, we’re using what’s known as an incrementor to increase the value of our variable by 1. The double parenthesis tells the shell that we’re doing an arithmetic operation, so the interpreter doesn’t think that we’re working with strings.
doneWhen we’re done writing a while loop, we must close the block with done. If you’ve typed the script properly, it should count from 1 to 15.
Another type of loop is a for loop. A for loop executes a statement for every item in a set. For example, you can have the for loop execute a command against every file in a directory. Consider this example:
#!/bin/bashturtles='Donatello Leonardo Michelangelo Raphael'for t in $turtlesdo echo $tdoneLet’s take a deeper look into what we’ve done here:
turtles='Donatello Leonardo Michelangelo Raphael'Here, we’re creating a list and populating it with names. Each name is one item in the list. We’re calling this list turtles. We can see the contents of this list with echo as we would with any other variable:
echo $turtlesNext, let’s look at how we set up the for loop:
for t in $turtlesNow, we’re telling the interpreter to prepare to do something for every item in the list. The t here is arbitrary, we could’ve used any letter here or even a longer string. We’re just setting up a temporary variable we want to use in order to hold the current item the script is working on.
doWith do, we’re telling the for loop to prepare itself to start doing something.
echo $tNow, we’re printing the current value of $t to stdout.
doneJust as we did with the while loop, we type done to let the interpreter know this is the end of the for loop. Effectively, we just created a for loop to print each item in a list independently:
DonatelloLeonardoMichelangeloRaphaelWe included four turtle names in our list, and we were able to iterate through them and print them out, one by one.
As much as I love turtles (especially the teenage mutant ninja variety), that script isn’t very practical or useful to us for server administration. Next, we’re going to write a script that can actually be quite useful.
Putting it all together – Writing an rsync backup script
Section titled “Putting it all together – Writing an rsync backup script”Let’s close this chapter with a Bash script that will not only prove to be very useful but will also help you enhance your skills. The rsync utility is one of my favorites; it’s very useful for copying data from one place to another, as well as being helpful for setting up a backup job. Let’s use the following example rsync command to practice automation:
rsync -avb --delete --backup-dir=/backup/incremental/08-17-2022 /src /targetThis example rsync command uses the -a (archive) option, which retains the metadata of the file(s) it copies to the target, such as the timestamp and owner. The -v option gives us verbose output, so we can see exactly what rsync is doing. The -b option enables backup mode, which means that if a file on the target will be overwritten by a file from the source, the previous version of that file will be renamed so it won’t be overwritten. Combining these three options, we simplify it to -avb rather than typing -a -v -b. The --delete option tells rsync to delete any files in the target that aren’t present in the source (since we used -b, any file that is deleted will be retained).
The --backup-dir option tells rsync that any time a file would have been renamed in this way (or deleted), to instead just copy it to another directory. In this case, we send any files that would have been overwritten to the /backup/incremental/08-16-2022 directory.
Let’s script this rsync job. One problem we can fix in our script right away is the date that is present inside the directory we’re using for the --backup-dir. The date changes every day, so we shouldn’t be hardcoding this. Therefore, let’s start our script by addressing this:
curdate=$(date +%m-%d-%Y)We’re creating a variable called curdate. We’re setting it equal to the output of the $(date +%m-%d-%Y) command. You can execute date +%m-%d-%Y in your terminal window to see exactly what that does. In this case, putting a command (such as date) in parentheses and a dollar symbol means that we’re executing the command in a sub-shell. The command will run, and we’re going to capture the result of that command and store it in the curdate variable.
Next, let’s make sure rsync is actually installed, and install it if it’s not:
if [ ! -f /usr/bin/rsync ]; then sudo apt install -y rsyncfiHere, we’re simply checking to see whether rsync is not installed. If it’s not, we’ll install it via apt. This is similar to how we checked for the existence of apache2 earlier in this chapter.
Now, we add the final line:
rsync -avb --delete --backup-dir=/backup/incremental/$curdate /src /targetYou can definitely see the magic of variables in Bash now, if you haven’t already. We’re including $curdate in our command, which is set to whatever the current date actually is. When we put it all together, our script looks like this:
curdate=$(date +%m-%d-%Y)if [ ! -f /usr/bin/rsync ]; then sudo apt install -y rsyncfirsync -avb --delete --backup-dir=/backup/incremental/$curdate /src /targetThis script, when run, will run an rsync job that will copy the contents from /src to /target. (Be sure to change these directories to match the source directory you want to back up and the target where you want to copy it to.) The beauty of this is that /target can be an external hard drive or network share. So, in a nutshell, you can automate a nightly backup. This backup, since we used the -b option along with --backup-dir, will allow you to retrieve previous versions of a file from the /backup/incremental directory. Feel free to get creative here as far as where to place previous file versions and where to send the backup.
Of course, don’t forget to mark the script as executable, assuming it was saved with a name like backup.sh:
chmod +x backup.shAt this point, you can put this script in a cron job to automate its run. To do so, it’s best to put the script in a central location where it can be found, such as in /usr/local/bin:
sudo mv backup.sh /usr/local/binYou can consider creating a cron job for this script to be run periodically. We’ll cover that in Chapter 7, Controlling and Monitoring Processes, which is the very next chapter. With a cron job, you can set up various tasks to run at different times in order to make your server essentially do your work for you.
Summary
Section titled “Summary”In this chapter, we dived into a number of more advanced concepts relating to shell commands, such as redirection, Bash history, command aliases, some command-line tricks, and more. Working with the shell is definitely something you’ll continue to improve upon, so don’t be worried if you have any trouble committing all of this knowledge to memory. After over 20 years of working with Linux, I’m still learning new things myself. The main takeaway in this chapter is to serve as a starting point to broaden your command-line techniques and also serve as the basis for future exploration into the subject.
In the next chapter, we’ll take a look at managing processes, which will include job management, taming misbehaving processes, and more. See you there!
Relevant videos
Section titled “Relevant videos”- Linux Crash Course – Bash History (LearnLinuxTV): https://linux.video/le-bash-history
- Linux Command-Line Tips & Tricks (LearnLinuxTV): https://linux.video/cli-tips