Interpreting Commands
local graph
Chapter 2 — Interpreting Commands
Section titled “Chapter 2 — Interpreting Commands”To fulfill its job as the interface between the user and the operating system kernel, a shell has to perform five different functions. These functions include interpreting commands, setting variables, enabling input/output redirection, enabling pipelines, and allowing customization of a user’s working environment. In this chapter, we’ll look at how bash and zsh interpret commands. As an added bonus, much of what we’ll cover in the next few chapters will also help you prepare for certain Linux certification exams, such as the Linux Professional Institute or CompTIA Linux+ exams.
Topics in this chapter include:
- Understanding the structure of a command
- Executing multiple commands at once
- Running commands recursively
- Understanding the command history
- Escaping and quoting
To follow along, you can use pretty much any Linux distro that you desire, as long as it’s running with either bash or zsh. Your best bet is to use a virtual machine instead of your production workstation, in case you accidentally delete or change something that you shouldn’t.
Understanding the Structure of a Command
A handy thing to know for both real-life and any certification exams that you may take, is the structure of a command. Commands can consist of up to three parts, and there’s a certain order for the parts. Here are the parts and the order in which you’ll normally place them:
- The command itself
- Command options
- Command arguments
If you plan to take a Linux certification exam, you’ll definitely want to remember this ordering rule. Later on though, we’ll see that some commands don’t always follow this rule.
Using Command Options
Section titled “Using Command Options”There are two general types of option switches:
- Single-letter options: For most commands, a single-letter option is preceded by a single dash. Most of the time, two or more single-letter options can be combined with a single dash.
- Whole-word options: For most commands, a whole word option is preceded by two dashes. Two or more whole-word options must be listed separately, because they can’t be combined with a single pair of dashes.
To show you what we mean, check out this hands-on lab.
Hands-on Lab – Practice With Command Options
Section titled “Hands-on Lab – Practice With Command Options”In this lab, we’ll be working with the humble ls utility. Options and arguments are optional for this utility, so we’ll get to see the different configurations for the command in this hands-on practice.
- Let’s issue the naked ls command in order to see the files and directories that are in our current directory.
[donnie@fedora ~]$ ls4-2_Building_an_Alpine_Container.bak Public4-2_Building_an_Alpine_Container.pptx pwsafe.keyaddresses.txtcontaineralma9_default.txtalma9_future.txtalma_link.txtme.first......pCloudDrivePictures[yad-form.sh]- Now, let’s add a single-letter option. We’ll use the -l option to show the files and directories with some of their characteristics.
[donnie@fedora ~]$ ls -ltotal 40257473-rw-r--r--. 1 donnie donnie 754207 Apr 5 16:13 4-2_Building_an_Alpine_Container.bak-rw-r--r--. 1 donnie donnie 761796 Apr 8 14:49 4-2_Building_an_Alpine_Container.pptx-rw-r--r--. 1 donnie donnie 137 Apr 2 15:05 addresses.txt-rw-r--r--. 1 donnie donnie 1438 Nov 2 2022 alma9_default.txt...- Use the ls command with the -a option to see any hidden files or directories. (Hidden files or directories have names that begin with a period.)
[donnie@fedora ~]$ ls -a..pcloud..4-2_Building_an_Alpine_Container.bak Pictures4-2_Building_an_Alpine_Container.pptx .pkiaddresses.txtdesktopalma9_default.txt....mozilla.XauthorityMusic.xscreensaverNetRexxerrorsniktoform.sh[donnie@fedora ~]$- Next, let’s combine the two options, so that we can see the characteristics of both the hidden and unhidden files and directories:
[donnie@fedora ~]$ ls -latotal 40257561drwx------. 1 donnie donnie 2820 Jul 25 13:53 .drwxr-xr-x. 1 root root 12 Aug 9 2022 ..-rw-r--r--. 1 donnie donnie 137 Apr 2 15:05 addresses.txt-rw-------. 1 donnie donnie 15804 Jul 24 17:53 .bash_history-rw-r--r--. 1 donnie donnie 18 Jan 19 2022 .bash_logout-rw-r--r--. 1 donnie donnie 194 Apr 3 12:11 .bash_profile-rw-r--r--. 1 donnie donnie 513 Apr 3 12:11 .bashrc...In the preceding examples, the donnie donnie part indicates that the files and directories belong to user donnie and are associated with the donnie group. In this example, we’re using a whole-word option, —author, preceded by two dashes, to view some extra information. Let’s use this —author witch and the -l switch together to see who authored these files:
[donnie@fedora ~]$ ls -l --authortotal 40257473-rw-r--r--. 1 donnie donnie donnie 137 Apr 2 15:05 addresses.txt-rw-r--r--. 1 donnie donnie donnie 1438 Nov 2 2022 alma9_default.txt-rw-r--r--. 1 donnie donnie donnie 1297 Nov 2 2022 alma9_future.txt......-rwxr--r--. 1 donnie donnie donnie 263 May 16 15:42 yad-form.sh[donnie@fedora ~]$So, it appears that that Donnie character also created the files in the first place. (Oh, that’s me, isn’t it?)
Using Command Arguments
An argument is an object upon which a command will operate. For the ls command, an argument would be the name of a file or directory. For example, let’s say that we want to see the details of just a certain file. We can do something like this:
[donnie@fedora ~]$ ls -l yad-form.sh-rwxr--r--. 1 donnie donnie 263 May 16 15:42 yad-form.sh[donnie@fedora ~]$We can use the * wildcard to see details of all files of a certain type, like so:
[donnie@fedora ~]$ ls -l *.sh-rwxr--r--. 1 donnie donnie 116 May 16 15:04 root.sh-rwxr--r--. 1 donnie donnie 263 May 16 15:42 yad-form.sh[donnie@fedora ~]$If you’re not familiar with the concept of wildcards, think of them as a way to perform pattern-matching. In the above example, the * wildcard is used to match one or more characters. For this reason, the ls -l *.sh command allows us to see all files with the .sh filename extension. You can also use this wildcard in other ways. For example, to see all filenames and directory names that begin with the letter w, just do this
donnie@opensuse:~> ls -ld w*drwxrwxr-x 1 donnie users 22 Mar 5 2022 windows-rw-r--r-- 1 donnie users 82180 Dec 7 2019 wingding.ttfdrwxr-xr-x 1 donnie users 138 Mar 11 2023 wowner-x86_64-linux-gnu-v0.11donnie@opensuse:~>For more information about wildcards, check out the reference in the Further Reading section.
In this case, we’re looking at all files whose names end in .sh.
You’re not always limited to specifying just one argument. In this example, we’re looking at three different files:
[donnie@fedora ~]$ ls -l missing_stuff.txt yad-form.sh Dylan-My_Back_Pages-tab.odt-rw-r--r--. 1 donnie donnie 29502 Mar 7 18:30 Dylan-My_Back_Pages-tab.odt-rw-r--r--. 1 donnie donnie 394 Dec 7 2022 missing_stuff.txt-rw-r--r--. 1 donnie donnie 263 May 16 15:42 yad-form.sh[donnie@fedora ~]$Use the -ld option to view the characteristics of a directory without viewing the contents of the directory, like so:
[donnie@fedora ~]$ ls -ld Downloads/drwxr-xr-x. 1 donnie donnie 8100 Aug 4 12:37 Downloads/[donnie@fedora ~]$Although you can actually change the order in which options and arguments appear in many commands, it’s bad practice to do so. To avoid confusion and to prepare yourself for any Linux certifications exams that you might take, just follow the ordering rule that I’ve presented here. That is, the command itself, command options, and lastly, the command arguments.
That about does it for the command structure part. Let’s move on to see how to execute multiple commands at once.
Executing Multiple Commands at Once
Section titled “Executing Multiple Commands at Once”From either the command-line or from within shell scripts, it’s handy to know how to combine multiple commands into one single command. In this section, I’ll demonstrate three ways to do that which are:
- Running commands interactively
- Using command sequences
- Using the find utility
Running Commands Interactively
Section titled “Running Commands Interactively”This is a form of shell-script programming, except that you’re just executing all commands from the command-line, instead of actually writing, saving, and executing a script. Here, you are creating a for loop — with each command of the loop on its own separate line — to perform a directory listing three times.
[donnie@fedora ~]$ for var in arg1 arg2 arg3> do> echo $var> ls> done......[donnie@fedora ~]$At the end of each line, you’ll hit the Enter key. But, nothing will happen until you type the done command on the final line. The for loop will then run three times, once for each of the three listed arguments. Each time that it runs, the value of an argument gets assigned to the var variable, and the echo command prints the currently-assigned value. The output will look something like this:
arg14-2_Building_an_Alpine_Container.bak Public4-2_Building_an_Alpine_Container.pptx pwsafe.keyarg24-2_Building_an_Alpine_Container.bak Public4-2_Building_an_Alpine_Container.pptx pwsafe.keyarg34-2_Building_an_Alpine_Container.bak Public4-2_Building_an_Alpine_Container.pptx pwsafe.keyNext, hit the up arrow key on your keyboard, and you’ll see the for loop that you just executed. If you try this with bash, you’ll see that the individual commands are separated by semi-colons, like so:
[donnie@fedora ~]$ for var in arg1 arg2 arg3; do echo $var; ls; doneOn zsh, pressing the up arrow key will cause the command components to appear on their own separate lines, as you see here:
donnie@opensuse:~> for var in arg1 arg2 arg3doecho $varlsdoneEither way, the for loop will run again when you hit the Enter key.
If you’re still a bit unclear about how for loops work, have no fear. We’ll look at them in greater detail once we start actually creating shell scripts.
Using Command Sequences
Section titled “Using Command Sequences”Command sequences are another type of programming structure that you’ll find very useful. Here, I’m demonstrating how to use them from the command-line so that you can grasp the basic concepts. In the upcoming chapters, I’ll show you examples of how to use them in shell scripts.
Chaining Commands with a Semi-Colon
Section titled “Chaining Commands with a Semi-Colon”You can also use the semi-colon to separate stand-alone commands that you want to execute from the same command entry. If you wanted to cd to a certain directory and then look at its contents, you could enter each command on its own line. Or, you could enter them both on the same line. This process is called command chaining, which looks like this:
[donnie@fedora ~]$ cd /var ; lsaccount cache db ftp kerberos local log nis preserve spool ypadm crash empty games lib lock mail opt run tmp[donnie@fedora var]$[donnie@fedora ~]$ cd /far ; lsbash: cd: /far: No such file or directory4-2_Building_an_Alpine_Container.bak Public4-2_Building_an_Alpine_Container.pptx pwsafe.keyaddresses.txtalma9_default.txtpython_containerrad-bfgminer...The first command failed because I tried to cd into a non-existent directory. But, the second command still executed, which listed the files in my home directory.
Conditional Command Execution with Double Ampersands
You can also instruct bash or zsh to only execute the second command if the first command successfully completes. Just separate the commands with && instead of with a semi-colon, like this:
[donnie@fedora ~]$ cd /var && lsaccount cache db ftp kerberos local log nis preserve spool ypadm crash empty games lib lock mail opt run tmp[donnie@fedora var]$What if the first command doesn’t run successfully? Note here that the second command doesn’t execute:
[donnie@fedora ~]$ cd /far && lsbash: cd: /far: No such file or directory[donnie@fedora ~]$Conditional Command Execution with Double Pipes
If you want bash or zsh to execute the second command only if the first command doesn’t run successfully, just separate the commands with ||. (This is a pair of pipe characters, which you’ll find on the same key as the backslash.) To illustrate, let’s again make a slight typo while trying to change directories.
[donnie@fedora ~]$ ce /var || echo "This command didn't work."bash: ce: command not foundThis command didn't work.[donnie@fedora ~]$[donnie@fedora ~]$ cd /var || echo "This command didn't work."[donnie@fedora var]$For a more practical example, try changing to a directory, creating it if it doesn’t exist, and then changing to it after it’s been successfully created.
[donnie@fedora ~]$ cd mydirectory || mkdir mydirectory && cd mydirectorybash: cd: mydirectory: No such file or directory[donnie@fedora mydirectory]$You’ll still get an error message saying that the directory you tried to access doesn’t exist. But, look at the command prompt, and you’ll see that the directory has been created, and that you’re now in it.
Using the find Utility
We’ll now take a short intermission from our discussion of running multiple commands in order to introduce the find utility, which is truly the Cool-Mac Daddy of all search utilities. After this introduction, I’ll use find to show you more ways to run multiple commands at once.
Also, it would behoove us to mention that find isn’t just good for command-line searches. It’s also excellent for use within shell scripts, as you’ll see much later.
If you’re as old as I am, you might remember the Windows XP search pooch, which pranced around on your screen every time you did a file search from the Windows XP graphical search utility. It was cute, but it didn’t add to your search power. With the Linux find utility, you can perform powerful searches on just about any criterion you can think of, and then—from the same command-line entry—invoke another utility to do whatever you need to do with the search results. I won’t try to discuss every option there is for find, since there are so many. Rather, I’ll give you an overview of what you can do with find, and let you read its man page for the rest. (Just enter man find at the command-line to read about all of its options.)
In order to perform the most basic of searches, you’ll need to specify two things:
-
The search path: You can perform a search in either a specific path, or the entire filesystem. Since find is inherently recursive, the search will automatically extend to all of the subdirectories that are beneath of the directory that you specify. (Of course, you can also add command switches that limit the depth of the search.)
-
What you’re searching for: There are a lot of ways that you can specify this. You can search for files of a specific name, and decide whether to make the search case-sensitive. You can also use wildcards, or search for files with certain characteristics or that are of a certain age. Or, you can combine multiple criteria for even more specific searches. The main thing that limits you is your own imagination.
So now, let’s say that you want to search the entire filesystem for all files whose names end in .conf. You’ll want to use either the -name or the -iname switch in front of the file description that you want to search for. Otherwise, you’ll get a jumbled up mess of every directory listing that you’ve searched, with the information you’re looking for mixed in. For case-sensitive searches, use -name, and for case-insensitive searches, use -iname. In this case, we’ll use -iname, since we want to make the search case-insensitive.
I know, I’ve told you previously that most whole-word option switches are preceded by a pair of dashes. The find utility is an exception to the rule, because its whole-word option switches are preceded by only a single dash.
Also, be aware that searching through an entire filesystem on a production server with very large drives can take a long time. It’s sometimes necessary to do that, but it’s best to confine your searches to specific directories whenever possible.
If you include a wildcard character with a search criterion, you’ll need to enclose that search criterion in quotes. That will keep the shell from interpreting the wildcard character as an ambiguous file reference. For example, to perform a case-insensitive search through the current working directory and all of its subdirectories for all files with names ending with a .conf filename extension, I would do this:
[donnie@fedora ~]$ find -iname '*.conf'./cache/containers/short-name-aliases.conf./config/lxsession/LXDE/desktop.conf./config/pcmanfm/LXDE/desktop-items-0.conf./config/pcmanfm/LXDE/pcmanfm.conf./config/lxterminal/lxterminal.conf./config/Trolltech.conf......./tor-browser/Browser/TorBrowser/Data/fontconfig/fonts.conf./rad-bfgminer/example.conf./rad-bfgminer/knc-asic/RPi_system/raspi-blacklist.conf./something.CONF[donnie@fedora ~]$Using the -iname option, I was able to find files with names that ended in either .conf or .CONF. Had I used the -name option instead, I would only have found files with names that end in .conf.
Minimally, you would specify the search path as the first component of the find command. In the GNU implementation of find that’s included on Linux-based operating systems, omitting the search path will cause find to search through the current working directory, as we’ve just seen. Unfortunately, that trick doesn’t work for Unix/Unix-like operating systems, such as FreeBSD, macOS, or OpenIndiana. For those operating systems, you’ll always need to specify a search path. To make find search through the current working directory, just use a dot to specify the search path. So, on my FreeBSD virtual machine, the command looks like this:
donnie@freebsd-1:~$ find . -iname "*.conf"./anotherdir/yetanother.conf./anotherthing.CONF./something.confdonnie@freebsd-1:~$Okay, I know. You’re wondering why I’m mentioning FreeBSD, macOS, and OpenIndiana in what’s supposed to be a Linux book. Well, it’s because sometimes, we’ll want to create shell scripts that work on multiple operating systems, rather than just on Linux. If you include the dot in this command, it will still work on your Linux machines, and will also work on your Unix/Unix-like machines.
You can also specify search paths that aren’t your current working directory. For example, you can remain within your own home directory and search through the entire filesystem like this:
[donnie@fedora ~]$ find / -iname '*.conf'Of course, this will take much longer than it does to just search through one directory. Also, you’ll encounter errors because your normal user account won’t have permission to go into every directory. To search through all directories on the filesystem, just preface the command with sudo, like this:
You can perform searches with more than one search criterion. If you separate the criteria with a space, it will be the same as placing an and operator between them. Here, we’ll use the -mtime -7 switch to find all of the .conf files that were modified within the last seven days, and the -ls switch at the end to show detailed information about the files:
[donnie@fedora ~]$ sudo find / -iname '*.conf' -mtime -7 -ls 18 4 -rw-r--r-- 1 root root 328 Jul 24 17:50 /boot/loader/entries/81085aed13d34626859063e7ebf29da5-6.4.4-100.fc37.x86_64.conf 332176 4 -rw-r--r-- 1 donnie donnie 467 Jul 24 16:14 /home/donnie/.config/pcmanfm/LXDE/pcmanfm.conf 370 4 -rw-r--r-- 1 donnie donnie 3272 Jul 19 16:21 /home/donnie/.config/Trolltech.conf... 4120762 8 -rw-r--r-- 2 root root 7017Jul 21 14:43 /var/lib/flatpak/app/com.notepadqq.Notepadqq/x86_64/stable/a049a1963430515aa15d950212fc1f0db7efb703a94dd1f1d316b38ad12ec72/files/lib/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/js1.node.conf[donnie@fedora ~]$To search for .conf files that were modified more than seven days ago, replace the -7 with +7, like this:
[donnie@fedora ~]$ sudo find / -iname '*.conf' -mtime +7 -lsIt’s also possible to create more advanced searches by creating compound expressions. It works like Algebra, in that expressions are evaluated from left to right unless you group some of the terms with parentheses. But, with that, there are a couple of minor catches.
Since the parenthesis symbols have a special meaning in bash and zsh, you’ll want to precede them with a backslash so that bash and zsh won’t interpret them the wrong way. You’ll also need to leave a space between the parenthesis symbols and the terms that they’re enclosing.
Let’s say that we now want to look for all of the .conf files in the /etc/ directory that were either modified within the last seven days, or that were accessed more than 30 days ago. We’ll use the -atime switch to set the access time criterion. The or operator is represented by -o.
[donnie@fedora ~]$ sudo find /etc -iname '*.conf' \( -mtime -7 -o -atime +30 \)[sudo] password for donnie:/etc/UPower/UPower.conf/etc/X11/xinit/xinput.d/ibus.conf/etc/X11/xinit/xinput.d/xcompose.conf/etc/X11/xinit/xinput.d/xim.conf.../etc/appstream.conf/etc/whois.conf/etc/nfsmount.conf[donnie@fedora ~]$There are several subdirectories in /etc/ that require root privileges to enter, so I used sudo again, as I did before. Adding the -ls option at the end of the command would show the timestamps on the files, which would tell me which of the two search criteria applies to each specific file.
If you want to find files that belong to only a certain user, you can do that with the -user switch. Add a second criterion to find only files of a certain type that belong to a certain user. Here, I’m searching through the whole filesystem for all .png graphics files that belong to me:
[donnie@fedora ~]$ sudo find / -user donnie -iname '*.png'/home/donnie/.cache/mozilla/firefox/xgwvyw2p.default-release/thumbnails/9aa3453b0b6246665eb573e58a40fe7c.png/home/donnie/.cache/mozilla/firefox/xgwvyw2p.default-release/thumbnails/96c0e5aa4c2e735c2ead0701d2348dd6.png
....../home/donnie/rad-bfgminer/vastairent.pngfind: '/run/user/1000/doc': Permission deniedfind: '/run/user/1000/gvfs': Permission denied/tmp/org.chromium.Chromium.Ipk3VA/pcloud1_16.pngfind: '/tmp/.mount_pcloudWz4ji1': Permission denied[donnie@fedora ~]$Even with full sudo privileges, there are still a couple of directories where I’m not allowed to access. But, that’s okay.
You can use the -group switch to find files that belong to a certain group. Here, I’m looking through my own home directory for either files or directories that are associated with the nobody group.
[donnie@fedora ~]$ sudo find -group nobody -ls3344421 0 drwxr-xr-x 1 nobody nobody 0 Jul 25 18:36 ./share3344505 0 -rw-r--r-- 1 donnie nobody 0 Jul 25 18:38 ./somefile.txt[donnie@fedora ~]$Note that I’m still using sudo here, because even in my own home directory there are some directories that find won’t access without it. (These are the directories that contain information about Docker containers.)
Conversely, you can use the -nogroup switch to find files that don’t belong to any group that’s listed in the /etc/group file.
[donnie@fedora ~]$ sudo find -nogroup./.local/share/containers/storage/overlay/994393dc58e7931862558d06e46aa2bb17487044f670f310dffe1d24e4d1eec7/diff/etc/shadow./.local/share/containers/storage/overlay/ded7a220bb058e28ee3254fbba04ca90b679070424424761a53a043b93b612bf/diff/etc/shadow./.local/share/containers/storage/overlay/8e012198eea15b2554b07014081c85fec4967a1b9cc4b65bd9a4bce3ae1c0c88/diff/etc/shadow./.local/share/containers/storage/overlay/7cd52847ad775a5ddc4b58326cf884beee34544296402c6292ed76474c686d39/diff/etc/shadow[donnie@fedora ~]$In the Linux/Unix world, everything on the system is represented by a file. Normal users of a system will usually just encounter regular files and directories, but there are many other types of files that will be of interest to a system administrator. The various file types include:
- Regular files: These are the types of files that a normal user would routinely access. Graphics files, video files, database files, spreadsheet files, text files, and executable files are all examples of regular files.
- Directories: It seems strange that a directory is a type of file, but that’s just how it is in the Linux and Unix worlds.
- Character devices: A character device either accepts or supplies a serial stream of data. A sound card or a terminal would be represented by a character device file. You’ll find these files in the /dev/ directory.
- Block devices: A block device file represents devices that can be accessed in a random manner. Examples include hard drives, solid-state drives, and drive partitions. You’ll also find these files in the /dev/ directory.
- Named pipes: These devices take the output from one system process and supply it as the input to another system process, thus enabling inter-process communication.
- Sockets: These are the same as named pipes, except that they can send and receive file descriptors as part of the communications stream. Also, unlike named pipes, sockets can allow two-way data exchange between two processes.
- Symbolic links: This type of file simply points to either a regular file or directory. This allows users to either access files and directories from multiple places in the filesystem, or to access them by different names.
You can tell what type a file is by doing an ls -l command. The first character in the output for each file is known as the file mode string. This file mode string designates the file type. For example, let’s look at what’s in my home directory:
[donnie@fedora ~]$ ls -l<!-- page: 043 (printed 28) -->total 137972-rw-r--r--. 1 donnie donnie 12111206 Feb 18 13:41 dnf_list.txtdrwxr-xr-x. 15 donnie donnie 4096 Jul 27 16:39 orphaned_filesdrwxr-xr-x. 2 donnie donnie 6 Jul 29 16:53 perm_demo-rw-r--r--. 1 donnie donnie 643 Mar 26 15:53 sample.json[donnie@fedora ~]$Lines that begin with a - represent a regular file, and lines that begin with a d represent a directory. The various file types are represented as follows:
| File mode string | File type |
|---|---|
| - | Regular file |
| d | Directory |
| c | Character device |
| b | Block device |
| p | Named pipe |
| s | Socket |
| l | Symbolic link |
Table 2.1: File type designators
There may be times when you’ll need to locate all files of a certain type. You can do that with the -type option, like so:
[donnie@fedora ~]$ sudo find / -type p -ls 545 0 prw------- 1 root root 0 Jul 31 15:20 /run/initctl 542 0 prw------- 1 root root 0 Jul 31 15:20 /run/dmeventd-client 541 0 prw------- 1 root root 0 Jul 31 15:20 /run/dmeventd-server 6 0 p---------- 1 donnie donnie 0 Jul 31 15:29 /run/user/1000/systemd/inaccessible/fifo 1228 0 prw------- 1 root root 0 Jul 31 15:21 /run/systemd/inhibit/2.ref 1193 0 prw------- 1 root root 0 Jul 31 15:21 /run/systemd/inhibit/1.ref 1324 0 prw------- 1 root root 0 Jul 31 15:29 /run/systemd/sessions/3.ref 1311 0 prw------- 1 root root 0 Jul 31 15:29 /run/systemd/sessions/1.ref 8 0 p---------- 1 root root 0 Jul 31 15:20 /run/systemd/inaccessible/fifo
<!-- page: 044 (printed 29) -->
112 0 prw------- 1 root root 0 Jul 31 15:20 /var/lib/nfs/rpc_pipefs/gssd/clntXX/gssd[donnie@fedora ~]$As you see, I’m using the -type p option to search for all named pipe files.
Now, let’s consider the previous example in which we searched for all files that end with a .conf filename extension:
[donnie@fedora ~]$ sudo find / -iname '*.conf'This command only found regular files because they’re the only types of files on the system that have the .conf filename extension. But, let’s now say that we want to search through the /etc/ directory to find all subdirectories with the conf text string in their names. If we don’t specify a file type, we’ll see regular files, symbolic links, and directories:
[donnie@fedora ~]$ sudo find /etc -name '*conf*' -ls329486 4 -rw-r--r-- 1 root root 351 Jul 27 07:02 /etc/dnf/plugins/copr.conf329487 4 -rw-r--r-- 1 root root 30 Jul 27 07:02 /etc/dnf/plugins/debuginfo-install.conf8480155 4 -rw-r--r-- 1 root root 93 May 18 04:27 /etc/dnf/protected.d/dnf.conf...25325169 0 lrwxrwxrwx 1 root root 43 Jul 29 18:19 /etc/crypto-policies/back-ends/bind.config -> /usr/share/crypto-policies/DEFAULT/bind.txt25325172 0 lrwxrwxrwx 1 root root 45 Jul 29 18:19 /etc/crypto-policies/back-ends/gnutls.config -> /usr/share/crypto-policies/DEFAULT/gnutls.txt...5430579 0 drwxr-xr-x 2 root root 25 Sep 19 2022 /etc/reader.conf.d8878157 0 drwxr-xr-x 3 root root 27 Dec 8 2022 /etc/pkgconfig8927250 0 drwxr-xr-x 2 root root 83 Nov 16 2022 /etc/krb5.conf.d...[donnie@fedora ~]$We’ll use the -type d option to narrow things down:
[donnie@fedora ~]$ sudo find /etc -name '*conf*' -type d -ls17060336 0 drwxr-xr-x 2 root root 41 Dec 8 2022 /etc/fonts/conf.d<!-- page: 045 (printed 30) -->25430579 0 drwxr-xr-x 2 root root 25 Sep 19 2022 /etc/reader.conf.d8878157 0 drwxr-xr-x 3 root root 27 Dec 8 2022 /etc/pkgconfig8927250 0 drwxr-xr-x 2 root root 83 Nov 16 2022 /etc/krb5.conf.d25313333 0 drwxr-xr-x 2 root root 6 Feb 1 17:58 /etc/security/pwquality.conf.d25395980 0 drwxr-xr-x 2 root root 30 Dec 8 2022 /etc/X11/xorg.conf.d17060487 0 drwxr-xr-x 2 root root 6 Aug 9 2022 /etc/pm/config.d......16917753 0 drwxr-xr-x 2 root root 33 Jul 29 18:11 /etc/containers/registries.conf.d[donnie@fedora ~]$We now only see the directories, which is exactly what we want.
As I said before, there are a lot of options that you can use with the find utility. (Enter man find to see them all.)
Now, with the introduction to find out of the way, let’s look at how to use find to perform multiple actions with one command.
Performing Multiple Actions with find
Section titled “Performing Multiple Actions with find”Our next trick contains a bit of a twist. We’ll use find’s -exec and -ok option switches to make find perform some sort of action on each file that it finds. First, find finds the files. Then, it causes another command to run that will take some sort of action on the files. Here’s how it works.
The -exec and -ok switches tell the shell to perform a second command only if the first command produces valid output. It then uses the output of the first command (find) as arguments for the second. The difference between the two switches is that -exec causes the desired action to automatically execute on each file without prompting the user. The -ok switch will cause the action to stop after each file that find finds, asking the user whether or not to proceed with the action for that file. Here, we’re searching the entire filesystem for all .zip files that are more than 30 days old, and copying them to the /home/donnie/ directory. (Note that I’m still using sudo so that I can access all directories.)
[donnie@fedora ~]$ sudo find / \(\ -mtime +30 -iname '*.zip' \) -exec cp {} /home/donnie \;The {} after the cp command tells bash or zsh, “Take the results from the find command, and put them here as the arguments”. Note that this command sequence has to end with a semi-colon. But, since the semi-colon has special meaning for bash and zsh, you must precede it with a backslash so that bash and zsh will interpret it correctly.
Also, note that you must have a blank space after the first parenthesis, and another blank space before the backslash that precedes the last parenthesis.
Now, suppose that you only want to copy over some of the files that you find. Just replace the -exec switch with the -ok switch. It works the same as -exec, but it will ask permission before performing an operation on a file. You’ll have to enter either y or n before continuing to the next file.
The same principle also works for removing files.
[donnie@fedora ~]$ sudo find / \( -mtime +30 -iname '*.zip' \) -ok rm {} \;Let’s now suppose that Vicky, Cleopatra, Frank, and Goldie are all creating graphics for some sort of project. They’re supposed to place the graphics files into the graphics subdirectory that each of them have in their own home directory. Sometimes they forget though, and place the files into their top-level home directories, as we see in the following diagram:
[!visual-conversion] Figure 2.1: Some of these graphics files are in the wrong place. Page scans unavailable; diagram reconstructed as ASCII from the in-text description.
/home|-- vicky| |-- graphics| | `-- project_graphic.png| `-- vicky_photo.png <- graphics file in the wrong place|-- cleopatra| |-- graphics| | `-- project_graphic.png| `-- cleopatra_photo.png <- graphics file in the wrong place|-- frank| |-- graphics| | `-- project_graphic.png| `-- frank_photo.png <- graphics file in the wrong place`-- goldie |-- graphics | `-- project_graphic.png `-- goldie_photo.png <- graphics file in the wrong placeNow, let’s get a bit of hands-on practice with this.
Hands-on Lab – Using find to Perform Other Commands
For this lab, use a Fedora, Debian, or Ubuntu virtual machine. (I’ll provide instructions for all of them.)
Let’s say that we want to copy everyone’s graphics files into a common backup directory.
- First, create the /backup directory, like this:
[donnie@fedora ~]$ sudo mkdir /backupFor our present purposes, just leave ownership and permissions settings as they are.
- Next, create user accounts for Vicky, Cleopatra, Frank, and Goldie, and assign a password to each account. On Fedora, the commands would look like this:
donnie@fedora:~$ sudo useradd frankdonnie@fedora:~$ sudo passwd frankOn either Debian or Ubuntu, use the interactive adduser command, which both creates the user account and sets the password. It looks like this:
donnie@debian12:~$ sudo adduser goldie- Log into each user’s account, create a graphics directory in each user’s home directory, and then create some fake graphics files. Here are the commands to do that:
goldie@fedora:~$ touch goldie02.pnggoldie@fedora:~$ mkdir graphicsgoldie@fedora:~$ cd graphics/goldie@fedora:~/graphics$ touch {goldie01.png,goldie03.png,goldie04.png}goldie@fedora:~/graphics$The touch command is actually meant to be used by programmers for purposes that I won’t go into here. But, it’s also handy for situations like this, when you just need to create some fake files for testing purposes. By enclosing a comma-separated list of filenames within a pair of curly braces, you can create multiple files with just one single command. To verify that, let’s peek into the graphics directory:
goldie@fedora:~/graphics$ ls -ltotal 0-rw-r--r--. 1 goldie goldie 0 Mar 23 13:27 goldie01.png-rw-r--r--. 1 goldie goldie 0 Mar 23 13:27 goldie03.png-rw-r--r--. 1 goldie goldie 0 Mar 23 13:27 goldie04.pnggoldie@fedora:~/graphics$- For this step, you’ll need to log back into your own user account. You want to be sure to get all of the graphics files, even if they’re in the users’ top-level home directories, and copy them into the /backup/ directory. Your command and results would look like this:
[donnie@fedora ~]$ sudo find /home -name '*.png' -exec cp {} /backup \;[donnie@fedora ~]$ ls -l /backup/total 0-rw-r--r--. 1 root root 0 Jul 28 15:40 cleopatra01.png-rw-r--r--. 1 root root 0 Jul 28 15:40 cleopatra02.png-rw-r--r--. 1 root root 0 Jul 28 15:40 cleopatra03.png<!-- page: 048 (printed 33) -->-rw-r--r--. 1 root root 0 Jul 28 15:40 cleopatra04.png-rw-r--r--. 1 root root 0 Jul 28 15:40 frank01.png-rw-r--r--. 1 root root 0 Jul 28 15:40 frank02.png-rw-r--r--. 1 root root 0 Jul 28 15:40 frank03.png-rw-r--r--. 1 root root 0 Jul 28 15:40 frank04.png-rw-r--r--. 1 root root 0 Jul 28 15:40 goldie01.png-rw-r--r--. 1 root root 0 Jul 28 15:40 goldie02.png-rw-r--r--. 1 root root 0 Jul 28 15:40 goldie03.png-rw-r--r--. 1 root root 0 Jul 28 15:40 goldie04.png-rw-r--r--. 1 root root 0 Jul 28 15:40 vicky01.png-rw-r--r--. 1 root root 0 Jul 28 15:40 vicky02.png-rw-r--r--. 1 root root 0 Jul 28 15:40 vicky03.png-rw-r--r--. 1 root root 0 Jul 28 15:40 vicky04.png[donnie@fedora ~]$What I’ve shown you here just barely scratches the surface of what you can do with find. To see the complete list of search criteria that you can specify, open the find man page and scroll down to the TESTS section.
We’ll look at some more find examples a bit later. For now though, let’s look at how to create recursive commands.
Running Commands Recursively
We’ve already shown you that the find utility is inherently recursive. That is, it will automatically search through the subdirectories of your specified search path without you having to tell it to. Most Linux commands aren’t that way, however. If you want them to work recursively, you’ll have to tell them to. For the most part, this is done with either the -R switch or the -r switch. (Some commands use -R, and some use -r. Something that you’ll eventually see for yourself is that there’s not a lot of consistency in how the different commands work with option switches.) Let’s see how it all works with a hands-on lab.
The examples in this section involve using the numeric method to set file and directory permissions. For anyone who’s not familiar with how to do that, I’ve provided a reference in the Further Reading section.
Hands-on Lab – Using Commands with Recursion
In this lab, you’ll be using the recursive option for the ls and chmod utilities. Let’s dig in.
First, let’s create a new directory with a set of nested subdirectories, like this:
[donnie@fedora ~]$ sudo mkdir -p /perm_demo/level1/level2/level3/level4[donnie@fedora ~]$Next, we want to look at the permissions settings for the entire nest of directories. So, let’s do this:
[donnie@fedora ~]$ ls -l /perm_demo/total 0drwxr-xr-x. 3 root root 20 Jul 29 17:09 level1[donnie@fedora ~]$Well now, that doesn’t help, does it? All we can see is just the first level subdirectory.
Let’s try adding the -R option to see if that helps:
[donnie@fedora ~]$ ls -lR /perm_demo//perm_demo/:total 0drwxr-xr-x. 3 root root 20 Jul 29 17:09 level1
/perm_demo/level1:total 0lrwxr-xr-x. 3 root root 20 Jul 29 17:09 level2
/perm_demo/level1/level2:total 0drwxr-xr-x. 3 root root 20 Jul 29 17:09 level3
/perm_demo/level1/level2/level3:total 0drwxr-xr-x. 2 root root 6 Jul 29 17:09 level4
/perm_demo/level1/level2/level3/level4:total 0[donnie@fedora ~]$This is much better, because we now see the permissions settings for all four of the nested subdirectories. But, we see that the permissions settings aren’t what we want. With the 755 permission setting that we currently have, we’re allowing the user to have read/write/execute access, while the group and others have read/execute access. What we really want is for the user and the group to both have read/write/execute access, and for others to have no access at all. We’ll do that by using chmod to change the permissions settings to 770. The -R switch will allow us to change the settings for the top-level directory, as well as all four of the nested subdirectories.
Recursively set the correct permissions setting with this command:
[donnie@fedora ~]$ sudo chmod -R 770 /perm_demo/[donnie@fedora ~]$Now that you’ve removed access for others, you’ll need to use sudo to view the permissions settings:
[donnie@fedora ~]$ sudo ls -lR /perm_demo//perm_demo/:total 0drwxrwx---. 3 root root 20 Jul 29 17:09 level1
/perm_demo/level1:total 0drwxrwx---. 3 root root 20 Jul 29 17:09 level2
/perm_demo/level1/level2:total 0drwxrwx---. 3 root root 20 Jul 29 17:09 level3
/perm_demo/level1/level2/level3:total 0drwxrwx---. 2 root root 6 Jul 29 17:09 level4
/perm_demo/level1/level2/level3/level4:total 0[donnie@fedora ~]$You see that the permissions setting is now 770 for the entire nest, which means that we have achieved extreme coolness.
Tip You might, at some point, be called upon to create a shell script that will automatically compile and install a program. The ability to create nested directories and recursively change permissions settings on them will come in quite handy when writing those kinds of scripts.
There are several other utilities that also have the recursive feature. (You’ll encounter some of them as you go through this book.) The slight catch is that for some of them the recursive option switch is -r, and for other it’s -R. But, that’s okay. When in doubt, just consult the man page for the utility that you need to use.
Now that we’ve covered recursion, let’s have a history lesson.
Understanding the Command History
Whenever you work with the command-line, there will be times when you’ll have to enter some commands more than once. If you’ve just entered a command that’s long and complex, you may not exactly be thrilled at the prospect of having to type it in all over again. Not to worry, though. For this, bash and zsh give you the ability to recall and/or edit commands that you’ve previously entered. There are a few ways to do this.
Whenever you enter a command, it gets stored in memory until you exit the shell session. The command will then get added to a file that’s specified by the HISTFILE variable. Usually, this is the .bash_history file on bash, and the .histfile file on zsh. You’ll find these stored in each user’s home directory. To verify that, you can use the echo command, like this:
[donnie@fedora ~]$ echo $HISTFILE/home/donnie/.bash_history[donnie@fedora ~]$On zsh, you’ll see this:
donnie@opensuse:~> echo $HISTFILE/home/donnie/.histfiledonnie@opensuse:~>The number of commands that get saved to either the .bash_history file or the .histfile is set by the HISTSIZE variable in the /etc/profile file. (Both bash and zsh reference the same file.) You can use grep to search for that line without having to open the file, like so:
[donnie@fedora ~]$ grep HISTSIZE /etc/profileHISTSIZE=1000export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL[donnie@fedora ~]$You can also use echo to see the setting:
[donnie@fedora ~]$ echo $HISTSIZE1000[donnie@fedora ~]$Either way, we see that the system is set up to store the last 1,000 user commands in the .bash_history file.
More often than not, you’ll probably use the up and down arrow keys on your keyboard to call up previously entered commands. If you keep pressing the up arrow key, you’ll scroll through the list of previous commands, starting with the last one entered. If you go past the command that you want, you can use the down arrow key to get back to it. When you finally do get to the command that you want to repeat, you can either press the Enter key to enter it as is, or edit it and then press Enter.
You can also use the ! in various ways to recall past commands. For example, entering !! will execute the last command that you entered, as you see here:
[donnie@fedora ~]$ ls -l *.txt-rw-r--r--. 1 donnie donnie 12111206 Feb 18 13:41 dnf_list.txt-rw-r--r--. 1 donnie donnie 2356 Jul 29 18:46 md5sumfile.txt-rw-r--r--. 1 donnie donnie 2356 Jul 29 18:49 newmdsums.txt[donnie@fedora ~]$ !!ls -l *.txt<!-- page: 052 (printed 37) -->-rw-r--r--. 1 donnie donnie 12111206 Feb 18 13:41 dnf_list.txt-rw-r--r--. 1 donnie donnie 2356 Jul 29 18:46 md5sumfile.txt-rw-r--r--. 1 donnie donnie 2356 Jul 29 18:49 newmd5sums.txt[donnie@fedora ~]$Use the ! followed by a text string to execute the last executed command that begins with that string. Let’s say that I want to repeat the last grep command that I did, like this:
[donnie@fedora ~]$grep HISTSIZE /etc/profileHISTSIZE=1000export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL[donnie@fedora ~]$Use !? followed by a string to execute the last executed command that contains that string, like this:
[donnie@fedora ~]$echo "The fat cat jumped over the skinny dog."The fat cat jumped over the skinny dog.[donnie@fedora ~]$!?echo "The fat cat jumped over the skinny dog."The fat cat jumped over the skinny dog.[donnie@fedora ~]$Now, for the coolest part of all. First, let’s view the history list, like so:
[donnie@fedora ~]$1 sudo dnf -y upgrade2 sudo shutdown -r nowj3 sudo shutdown -r now4 cd /usr/share......478 echo "The fat cat jumped over the skinny dog."479 clear[donnie@fedora ~]$To execute a command from this list, enter ! followed by the command number. For example, to perform the echo command again, enter !478, like so:
[donnie@fedora ~]$!478echo "The fat cat jumped over the skinny dog."The fat cat jumped over the skinny dog.[donnie@fedora ~]$Of all of the history tricks that I’ve shown you, this last one is the most useful one for me. But wait, here’s yet one more trick that you might find useful. That is, you can display the command history along with timestamps that show when each command has been executed. On bash, just do this:
donnie@opensuse:~> HISTTIMEFORMAT="%d/%m/%y %T " historyThe output will look something like this:
49 22/03/24 14:02:29 ./start_mining.sh50 22/03/24 14:02:29 vim start_mining.sh51 22/03/24 14:02:29 ./start_mining.sh52 22/03/24 14:02:29 cd53 22/03/24 14:02:29 cd Downloads/54 22/03/24 14:02:29 ls......1046 23/03/24 12:03:53 clear1047 23/03/24 12:05:37 HISTTIMEFORMAT="%d/%m/%y %T " historydonnie@opensuse:~>What’s happening here is that we’re configuring the HISTTIMEFORMAT environmental variable to display the timestamp in our desired format, and then running the history command.
This is somewhat easier on zsh, because zsh allows us to use history with the -f option switch, like so:
donnie@opensuse:~> zshdonnie@opensuse:~> history -f17 3/23/2024 11:58 echo $HISTFILE18 3/23/2024 11:58 cd /etc19 3/23/2024 11:58 ls20 3/23/2024 11:58 less zprofile......31 3/23/2024 11:58 echo $HISTFILE32 3/23/2024 11:58 exitdonnie@opensuse:~>Note that running history -f on bash will give you an error message, like this one:
donnie@opensuse:~> history -fbash: history: -f: invalid optionhistory: usage: history [-c] [-d offset] [n] or history -anrw [filename] orhistory -ps arg [arg...]donnie@opensuse:~>All right, let’s move on to the next topic.
Escaping and Quoting
Section titled “Escaping and Quoting”Whenever you type anything on the command-line or into a shell script, you’ll be using a mix of normal alphanumeric text and non-alphanumeric characters. Some of these characters have special meanings within the shell, and will cause the shell to perform in some special way. Sometimes, you’ll want the shell to interpret these special characters as normal text, instead of as something with a magical power. To do that, you can either escape or quote the special characters.
There are two general classes of characters that can be interpreted by the shell from within a shell command. These are:
- Normal characters: bash and zsh interpret these characters literally. In other words, they have no special meaning to the shell.
- Metacharacters: These characters have special meanings for bash and zsh. You could say that a metacharacter provides some sort of special instruction to these shells.
Here’s a space-separated list of metacharacters that can be used in either shell scripts or shell commands:
& ; | * ? ’ ” ` [ ] ( ) $ < > { } # / \ ! ~
I’d rather not try to explain what each one does right now, because many of them can perform multiple functions, depending upon the context of the command. But, we’ve already seen some of them in action, and we’ll see the rest of them in action as we progress through this book.
Escaping Metacharacters
Section titled “Escaping Metacharacters”We’ve already seen some of these metacharacters in action in the previous examples. To further demonstrate, let’s look at the humble * metacharacter, which can be used as a wildcard. Let’s first do a directory listing of all of the .conf files in the /etc/ directory, like so:
[donnie@fedora ~]$ ls /etc/*.conf/etc/anthy-unicode.conf /etc/libaudit.conf /etc/rsyncd.conf/etc/appstream.conf /etc/libuser.conf /etc/rsyslog.conf/etc/asound.conf /etc/locale.conf /etc/sestatus.conf....../etc/ld.so.conf /etc/resolv.conf[donnie@fedora ~]$You see that I’ve just listed all files with filenames that end with a .conf filename extension. Now, let’s place a \ in front of the *, like this:
[donnie@fedora ~]$ ls /etc/\*.confls: cannot access '/etc/*.conf': No such file or directory[donnie@fedora ~]$Placing the \ in front of the * caused the shell to interpret the * literally, instead of as a metacharacter. Instead of looking for all files with .conf at the end of their filenames, we’re now looking for just one specific file with the filename, *.conf. No such file exists, so ls returned an error message.
In our find example where we performed a compound search, we had to place a \ in front of each parenthesis character so that the shell would interpret them correctly. Here’s what that looked like:
[donnie@fedora ~]$ sudo find / \( -mtime +30 -iname '*.zip' \)/home/donnie/Downloads/Roboto_Condensed.zip/home/donnie/Downloads/Bungee_Spice.zip....../home/donnie/dosbox/turboc/SAMPLES/simpwn18/SWTCPPRJ.ZIP/home/donnie/dosbox/turboc/SAMPLES/simpwn18/SWH.ZIP/home/donnie/dosbox/turboc/SAMPLES/simpwn18/SIMPWIN.ZIP/home/donnie/dosbox/turboc/SAMPLES/simpwn18/SWTC.ZIP/home/donnie/dosbox/turbocplusplus/TC/TC.zip[donnie@fedora ~]$Now, let’s try it without the \ characters:
[donnie@fedora ~]$ sudo find / ( -mtime +30 -iname '*.zip' )bash: syntax error near unexpected token `('[donnie@fedora ~]$This time, I get an error message, because bash doesn’t understand what I’m trying to do.
Now, just for fun, try this pair of commands on your own machine and note the difference in output:
echo I won $300.echo I won \$300.I guess that I should mention that when you place a \ in front of a metacharacter so that the shell will interpret the metacharacter literally, it’s called escaping the metacharacter. This is something that you’ll use extensively for either normal shell commands or shell scripting.
Okay, let’s look at another way to make the shell interpret metacharacters literally.
Quoting
You sometimes might have to quote a text string when performing a shell command or writing a shell script. This simply involves surrounding the text string with either a pair of double quotes (”) or a pair of single quotes (’). If you surround a text string with a pair of single quotes, the shell will interpret any metacharacters that are within the quotes as normal, literal characters. If you surround a text string with a pair of double quotes, the shell will interpret most, but not all, metacharacters as normal, literal characters. To show how that works, let’s create a programming variable that we’ll call name, and assign to it the value charlie, like so:
[donnie@fedora ~]$ name=charlie[donnie@fedora ~]$Next, we’ll try to echo back the value of name, using a pair of single quotes:
[donnie@fedora ~]$ echo '$name'$name[donnie@fedora ~]$You see that the single quotes cause the shell to interpret the $ as a literal character. Now, let’s see what happen if we use a pair of double quotes:
[donnie@fedora ~]$ echo "$name"charlie[donnie@fedora ~]$This time, we see the variable’s actual value, because the $ is one of the metacharacters that the double quotes won’t treat as a literal character.
We’ll cover the topic of programming variables more in depth later. So for now, don’t stress out if you don’t fully understand the concept.
For reference, here’s the complete list of metacharacters that won’t get interpreted as literal characters by surrounding them with double quotes:
- ”
- \
- `
- $
To clarify, the list consists of the double quote character, the backslash, the back-tick, and the dollar sign. (For now, don’t worry about what all of these metacharacters do. We’ll cover them all in due time.)
For all other metacharacters, it doesn’t matter whether you use double quotes or single quotes. Let’s look at this example that uses a wildcard character:
[donnie@fedora ~]$ echo '*.txt'*.txt[donnie@fedora ~]$ echo "*.txt"*.txt[donnie@fedora ~]$Either way, the result is the same. Both times, the * gets treated as a literal character. To use the * as an actual metacharacter, just omit the quotes, like so:
[donnie@fedora ~]$ echo *.txtaddresses.txt alma9_default.txt alma9_future.txt alma_link.txt centos7scan_modified.txt centos7scan.txt dnf_list.txt finances.txt missing_stuff.txtpassword_for_RHEL_VM.txt rpmfusion.txt somefile.txt temp.txt test.txt text.txtubuntuscan_modified.txt ubuntuscan.txt withL3.txt withoutL3.txt[donnie@fedora ~]$Okay, that pretty much does it for escaping and quoting, as well as for the whole chapter. Let’s summarize and move on.
Summary
We’ve covered some important basics in this chapter. We started by describing the structure and the components of a shell command, and how to perform multiple actions with just one single command. Then, we looked at the find utility, and the cool things that you can do with it. We then looked at how to run commands recursively, and wrapped up with a discussion about escaping and quoting.
In the next chapter, we’ll talk about variables and pipelines. I’ll see you there.
Questions
-
Which of the following sets of metacharacters would cause the second command to run only if the first command runs successfully?
a. || b. && c. | d. &
-
You want to run a command that contains the $ metacharacter, but you want the shell to interpret the metacharacter literally. How would you do that? (Choose two.)
a. Precede the metacharacter with a /. b. Surround the text string that contains the metacharacter with a pair of single quotes. c. Precede the metacharacter with a .
d. Surround the text string that contains the metacharacter with a pair of double quotes. e. It’s not possible.
- You’re using find to search for files on a FreeBSD system. To search through the current working directory, what must you do on FreeBSD that you don’t have to do on Linux?
a. Use a dot to designate the search path. b. Nothing. The commands are performed the same way on both systems. c. This isn’t possible on a FreeBSD system. d. Use sudo.
- You want to create a nested directory structure with one single mkdir command. How would you do that?
a. Use the -r option to make mkdir run recursively. b. Use the -R option to make mkdir run recursively. c. Use the -P option. d. Use the -p option.
- You want to automatically perform an action on every file that find finds, without being prompted. Which find option would you use to do that?
a. -ok b. -exec c. —exec d. —ok
Further Reading
- Linux File Permissions Explained: https://www.redhat.com/sysadmin/linux-file-permissions-explained
- How to Use Bash Wildcards for Globbing?: https://www.shell-tips.com/bash/wildcards-globbing/#gsc.tab=0
- How to Recursively Search Directory Names in Linux: https://www.howtogeek.com/devops/how-to-recursively-search-directory-names-in-linux/
- Find Command in Linux: https://linuxize.com/post/how-to-find-files-in-linux-using-the-command-line/
- 10 Ways to Use the Linux find Command: https://www.redhat.com/sysadmin/linux-find-command
- What are Linux Metacharacters? Everything You Need to Know: https://www.makeuseof.com/what-are-linux-metacharacters/
- 6 Linux metacharacters I love to use on the command line: https://opensource.com/article/22/2/metacharacters-linux