Chapter 3. Step 3: Peeking at Files
Now that you know how to move around in the filesystem, it is time to learn about how to inspect the content of files. In this chapter, I show a few commands that allow you to look inside files safely, without changing them.
cat (concatenate) command dumps a file to the console, as shown in Figure 3-1.
We will be using
cat a lot in the rest of this report. Because most
Linux configuration and log files are text, this command is handy for
examining files, knowing that we can’t change them by accident. The
CMD.EXE equivalent is the
less Is More
less command paginates files or output, with each “page” based on
the size of the console window.
In Bash, as in Windows Command Prompt, the output from one command can be
redirected, or piped, to another command by using the
| character. In
Linux, where each command “does one thing, well,” it is common practice
to combine multiple commands, piping the output from one command to the
next to accomplish a series of tasks in sequence. For example, later in
this report you will see how to use the
ps command to produce a list
of running processes and then pipe that output to the
to search for a specific process by name. To demonstrate, although
can be passed a filename directly, here’s how to pipe command output
~ $ cat /etc/passwd | less
The output from
less clears the screen, and then shows the first page, as you can see in Figure 3-2.
The colon at the bottom of the screen indicates that
less is waiting for a
less displays its output, you have various navigation
Space, Page Down, or the down arrow scrolls down.
Page Up or the up arrow scrolls up.
/finds text searching forward (down) from the current cursor position, until the end of the file is reached; for example,
?finds text searching backward (up) from the current cursor position, until the beginning of the file is reached; for example,
nfinds next instance of the text you’re searching for (note that the meaning of this is reversed when using
pfinds previous instance of the text you’re searching for (note that the meaning of this is reversed when using
lesscommand and returns you to the prior view of the console.
tail command shows the last lines in a file. It is useful when
you’re looking at large log files and want to see just the last lines—for example, right after an error has occurred. By default,
tail will show the last 10 lines, but you can adjust the number of lines displayed with
-n parameter. For example, Figure 3-3 shows how to display just the last five lines.
tail command can also “follow” a file, remaining running and
showing new lines on the console as they are written to the file. This
is useful when you’re watching a log file for a new instance of an error
message, perhaps as you are testing to see if you can trigger the
condition by visiting a web page on the site that is throwing an error.
Figure 3-4 shows an example using the
-f parameter to follow a log file.