关于linux:Linuxhow-linux-work第二章-基本命令和目录层次结构

134次阅读

共计 75832 个字符,预计需要花费 190 分钟才能阅读完成。

第 2 章 Basic Commands and Directory Hierarchy(根本命令和目录层次结构)

This chapter is a guide to the Unix commands and utilities that will be referenced throughout this book. This is preliminary material, and you may already know a substantial amount of it. Even if you think you’re up to speed, take a few seconds to flip through the chapter just to make sure, especially when it comes to the directory hierarchy material in 2.19 Linux Directory Hierarchy Essentials.

本章是对 Unix 命令和实用工具的指南,这些内容将在本书中被援用。

这是初步资料,你可能曾经理解了其中相当多的内容。

即便你认为本人曾经把握了,也请花几秒钟翻阅本章,以确保无误,尤其是在波及 2.19 Linux 目录层次结构要点的局部。

Why Unix commands? Isn’t this a book about how Linux works? It is, of course, but Linux is a Unix flavor at heart. You’ll see the word Unix in this chapter more than Linux because you can take what you learn straight over to Solaris, BSD, and other Unix-flavored systems. I’ve attempted to avoid covering too many Linuxspecific user interface extensions, not only to give you a better background for using the other operating systems, but also because these extensions tend to be unstable. You’ll be able to adapt to new Linux releases much more quickly if you know the core commands.

为什么要学习 Unix 命令?这不是一本对于 Linux 如何工作的书吗?当然,它是的,但 Linux 实质上是一种 Unix 零碎。

在本章中,你会看到比 Linux 更多的 Unix 这个词,因为你所学到的货色能够间接利用于 Solaris、BSD 和其余 Unix 零碎。

我尽量避免涵盖太多 Linux 特定的用户界面扩大,不仅是为了给你应用其余操作系统提供更好的背景,而且因为这些扩大往往不稳固。

如果你理解外围命令,你将可能更快地适应新的 Linux 版本。

NOTE For more details about Unix for beginners than you’ll find here, consider reading The Linux Command Line (No Starch Press, 2012), UNIX for the Impatient (Addison-Wesley Professional, 1995), and Learning the UNIX Operating System, 5th edition (O’Reilly, 2001).

留神:如果你想要理解更多对于 Unix 初学者的细节,请思考浏览

《Linux 命令行》(No Starch Press,2012)、
《UNIX for the Impatient》(Addison-Wesley Professional,1995)和
《Learning the UNIX Operating System, 5th edition》(O’Reilly,2001)。

## 高兴的 Linux 命令行

2.1 The Bourne Shell: /bin/sh(伯恩 shell /bin/sh)

The shell is one of the most important parts of a Unix system. A shell is a program that runs commands, like the ones that users enter. The shell also serves as a small programming environment. Unix programmers often break common tasks into little components and use the shell to manage tasks and piece things together.

Shell 是 Unix 零碎中最重要的局部之一。

Shell 是一个运行命令的程序,就像用户输出的命令一样。

Shell 还充当一个小型的编程环境。

Unix 程序员常常将常见工作合成为小组件,并应用 Shell 来治理工作和组合事物。

Many important parts of the system are actually shell scripts—text files that contain a sequence of shell commands. If you’ve worked with MS-DOS previously, you can think of shell scripts as very powerful .BAT files. Because they’re important, Chapter 11 is devoted entirely to shell scripts.

许多零碎的重要局部实际上是 Shell 脚本——蕴含一系列 Shell 命令的文本文件。

如果你之前应用过 MS-DOS,能够将 Shell 脚本视为十分弱小的.BAT 文件。

因为它们很重要,第 11 章齐全专门解说了 Shell 脚本。

As you progress through this book and gain practice, you’ll add to your knowledge of manipulating commands using the shell. One of the best things about the shell is that if you make a mistake, you can easily see what you typed to find out what went wrong, and then try again.

随着你在本书中的学习和实际,你会一直减少应用 Shell 操作命令的常识。

Shell 最好的一点是,如果你犯了一个谬误,你能够轻松地看到你输出的内容,找出问题所在,而后再试一次。

There are many different Unix shells, but all derive several of their features from the Bourne shell (/bin/sh), a standard shell developed at Bell Labs for early versions of Unix. Every Unix system needs the Bourne shell in order to function correctly, as you will see throughout this book.

有许多不同的 Unix Shell,但它们都从 Bourne Shell(/bin/sh)派生了一些个性,这是贝尔实验室为晚期 Unix 版本开发的一个规范 Shell。

每个 Unix 零碎都须要 Bourne Shell 能力失常运行,这一点你将在本书中看到。

Linux uses an enhanced version of the Bourne shell called bash or the“Bourne-again”shell. The bash shell is the default shell on most Linux distributions, and /bin/sh is normally a link to bash on a Linux system. You should use the bash shell when running the examples in this book.

Linux 应用了一个增强版的 Bourne Shell,称为 bash 或“Bourne-again”Shell。

bash Shell 是大多数 Linux 发行版的默认 Shell,/bin/sh 通常是 Linux 零碎上 bash 的链接。

在运行本书中的示例时,应应用 bash Shell。

NOTE
You may not have bash as your default shell if you’re using this chapter as a guide for a Unix account at an organization where you’re not the system administrator. You can change your shell with chsh or ask your system administrator for help.

留神

如果你在应用本章作为 Unix 账户的指南,并且你不是系统管理员,则 bash 可能不是你的默认 Shell。

你能够应用 chsh 命令更改你的 Shell,或者向系统管理员寻求帮忙。

2.2 Use Shell(应用 Shell)

When you install Linux, you should create at least one regular user in addition to the root user; this will be your personal account. For this chapter, you should log in as the regular user.

装置 Linux 时,除了 root 用户外,还应创立至多一个普通用户,这就是 你的个人账户。

在本章中,你应以普通用户身份登录。

2.2.1 The Shell Window(shell 窗口)

After logging in, open a shell window (often referred to as a terminal). The easiest way to do so from a GUI like Gnome or Ubuntu’s Unity is to open a terminal application, which starts a shell inside a new window. Once you’ve opened a shell, it should display a prompt at the top that usually ends with a dollar sign ($). On Ubuntu, that prompt should look like name@host:path$, and on Fedora, it’s [name@host path]$. If you’re familiar with Windows, the shell window will look something like a DOS command prompt; the Terminal application in OS X is essentially the same as a Linux shell window.

登录后,关上一个 shell 窗口(通常称为终端)。

在相似 Gnome 或 Ubuntu Unity 的图形界面中,最简略的办法是关上一个终端应用程序,它会在一个新窗口中启动一个 shell。

一旦你关上了一个 shell,它应该在顶部显示一个提示符,通常以美元符号($)结尾。

在 Ubuntu 上,该提示符应该看起来像 name@host:path$,而在 Fedora 上,它是[name@host path]$。

如果你相熟 Windows,shell 窗口看起来会像 DOS 命令提示符;

在 OS X 中的终端应用程序实质上与 Linux 的 shell 窗口雷同。

This book contains many commands that you will type at a shell prompt. They all begin with a single $ to denote the shell prompt. For example, type this command (just the part in bold, not the $) and press ENTER:

这本书蕴含了许多你将在命令行提示符下输出的命令。

它们都以一个独自的 $ 符号结尾,用来表示命令行提示符。

例如,输出这个命令(只输出加粗局部,不包含 $ 符号),而后按回车键:

$ echo Hello there.

NOTE Many shell commands in this book start with #. You should run these as the superuser (root). These commands usually require extra caution.

留神

本书中的许多 shell 命令都以 # 结尾。

您应该以超级用户(root)身份运行这些命令。这些命令通常须要分外小心。

当初输出以下命令

$ cat /etc/passwd

This command displays the contents of the /etc/passwd system information file and then returns your shell prompt. Don’t worry about what this file does right now; you’ll learn all about it later, in Chapter 7.

该命令将显示 /etc/passwd 零碎信息文件的内容,而后返回 shell 提醒。

当初不必放心这个文件的作用,稍后你将在 第 7 章 中理解到它的全部内容。

2.2.2 cat

The cat command is one of the easiest Unix commands to understand; it simply outputs the contents of one or more files. The general syntax of the cat command is as follows:

cat 命令是最容易了解的 Unix 命令之一;

它简略地输入一个或多个文件的内容。

cat 命令的个别语法如下:

$ cat file1 file2 ...

When you run this command, cat prints the contents of file1, file2, and any other files that you specify (denoted by …), and then exits. The command is called cat because it performs concatenation when it prints the contents of more than one file.

当你运行这个命令时,cat 会打印文件 1、文件 2 以及你指定的其余文件(用 … 示意)的内容,而后退出。

cat 命令之所以被称为 cat,是因为当它打印多个文件的内容时,它执行了连贯操作。

2.2.3 Standard Input and Standard Output(规范输出和规范输入)

We’ll use cat to briefly explore Unix input and output (I/O). Unix processes use I/O streams to read and write data. Processes read data from input streams and write data to output streams. Streams are very flexible. For example, the source of an input stream can be a file, a device, a terminal, or even the output stream from another process.

咱们将应用 cat 命令简要摸索 Unix 的输出和输入(I/O)。

Unix 过程应用 I / O 流来读取和写入数据。过程从输出流读取数据,而后将数据写入输入流。

流非常灵活。

例如,输出流的源能够是文件、设施、终端,甚至是另一个过程的输入流。

To see an input stream at work, enter cat (with no filenames) and press ENTER. This time, you won’t get your shell prompt back because cat is still running. Now type anything and press ENTER at the end of each line. The cat command repeats any line that you type. Once you’re sufficiently bored, press CTRL-D on an empty line to terminate cat and return to the shell prompt.

为了看到输出流的工作原理,请输出 cat(不带文件名)并按下 ENTER 键。

这次,你不会立刻失去 shell 提示符,因为 cat 仍在运行。当初在每行的开端输出任何内容,而后按下 ENTER 键。

cat 命令会反复打印你输出的每一行。

当你感到足够无聊时,在空行上按下 CTRL- D 来终止 cat 并返回到 shell 提示符。

The reason cat adopted an interactive behavior has to do with streams. Because you did not specify an input filename, cat read from the standard input stream provided by the Linux kernel rather than a stream connected to a file. In this case, the standard input was connected to the terminal in which you ran cat.

cat 采纳交互行为的起因与流无关。

因为你没有指定输出文件名,所以 cat 从 Linux 内核提供的规范输出流中读取,而不是与文件连贯的流。

在这种状况下,规范输出与你运行 cat 的终端相连接。

NOTE Pressing CTRL-D on an empty line stops the current standard input entry from the terminal (and often terminates a program). Don’t confuse this with CTRL-C, which terminates a program regardless of its input or output.

留神 在空行上按下 CTRL- D 会进行从终端读取以后的规范输出(通常也会终止一个程序)。

不要将此与 CTRL- C 混同,后者无论输出或输入如何都会终止一个程序。

Standard output is similar. The kernel gives each process a standard output stream where it can write its output. The cat command always writes its output to the standard output. When you ran cat in the terminal, the standard output was connected to that terminal, so that’s where you saw the output.

规范输入相似。

内核为每个过程提供一个规范输入流,过程能够在其中写入输入。

cat 命令始终将其输入写入规范输入。

当你在终端上运行 cat 时,规范输入与该终端相连接,所以你在那里看到了输入。

Standard input and output are often abbreviated as stdin and stdout. Many commands operate as cat does; if you don’t specify an input file, the command reads from stdin. Output is a little different. Some commands (like cat) send output only to stdout, but others have the option to send output directly to files.

规范输出和输入通常缩写为 stdin 和 stdout。许多命令的操作形式与 cat 雷同;如果你没有指定输出文件,命令会从 stdin 读取。输入有些不同。有些命令(如 cat)只将输入发送到 stdout,但其余命令能够抉择间接将输入发送到文件。

There is a third standard I/O stream called standard error. You’ll see it in 2.14.1 Standard Error.

还有第三个规范 I / O 流称为规范谬误。你将在 2.14.1 规范谬误中看到它。

One of the best features of standard streams is that you can easily manipulate them to read and write to places other than the terminal, as you’ll learn in 2.14 Shell Input and Output. In particular, you’ll learn how to connect streams to files and other processes.

规范流的一个最好的个性是你能够轻松地操作它们以读取和写入除终端以外的其余中央,你将在 2.14 Shell 输出和输入中学到这一点。特地是,你将学习如何将流连接到文件和其余过程。

2.3 Basic Commands(根本命令)

Now let’s look at some more Unix commands. Most of the following programs take multiple arguments, and some have so many options and formats that an unabridged listing would be pointless. This is a simplified list of the basic commands; you don’t need all of the details just yet.

当初让咱们来看一些更多的 Unix 命令。以下大部分程序承受多个参数,并且有些命令有很多选项和格局,残缺的列表是没有意义的。

这是一个简化的根本命令列表;你当初不须要所有的细节。

2.3.1 ls

The ls command lists the contents of a directory. The default is the current directory. Use ls -l for a detailed (long) listing and ls -F to display file type information. (For more on the file types and permissions displayed in the left column below, see 2.17 File Modes and Permissions.) Here is a sample long listing; it includes the owner of the file (column 3), the group (column 4), the file size (column 5), and the modification date/time (between column 5 and the filename):

ls 命令列出一个目录的内容。默认是当前目录。

应用 ls - l 能够显示具体(长)列表,应用 ls -F 能够显示文件类型信息。

(无关左列中显示的文件类型和权限的更多信息,请参见 2.17 文件模式和权限。)

以下是一个示例长列表;它包含文件的

  • 所有者(第 3 列)
  • 组(第 4 列)
  • 文件大小(第 5 列)
  • 批改日期 / 工夫(在第 5 列和文件名之间)
$ ls -l
总计 3616
-rw-r--r-- 1 juser users 3804 Apr 30 2011 abusive.c
-rw-r--r-- 1 juser users 4165 May 26 2010 battery.zip
-rw-r--r-- 1 juser users 131219 Oct 26 2012 beav_1.40-13.tar.gz
-rw-r--r-- 1 juser users 6255 May 30 2010 country.c
drwxr-xr-x 2 juser users 4096 Jul 17 20:00 cs335
-rwxr-xr-x 1 juser users 7108 Feb 2 2011 dhry
-rw-r--r-- 1 juser users 11309 Oct 20 2010 dhry.c
-rw-r--r-- 1 juser users 56 Oct 6 2012 doit
drwxr-xr-x 6 juser users 4096 Feb 20 13:51 dw
drwxr-xr-x 3 juser users 4096 May 2 2011 hough-stuff

You’ll learn more about the d in column 1 of this output in 2.17 File Modes and Permissions.

对于此输入中第 1 列的 d,您将在 2.17 文件模式 和权限中理解更多信息。

2.3.2 cp

In its simplest form, cp copies files. For example, to copy file1 to file2, enter this:

cp 命令用于复制文件。

例如,要将 file1 复制到 file2,输出以下命令:

cp file1 file2

To copy a number of files to a directory (folder) named dir, try this instead:

要将多个文件复制到名为 dir 的目录(文件夹),能够尝试以下命令:

cp file1 ... fileN dir

2.3.3 mv

The mv (move) command is like cp. In its simplest form, it renames a file. For example, to rename file1 to file2, enter this:

mv(挪动)命令与 cp 相似。在其最简略的模式中,它用于重命名文件。

例如,要将 file1 重命名为 file2,输出以下命令:

mv file1 file2

您还能够应用 mv 将多个文件挪动到不同的目录:

mv file1 ... fileN dir

2.3.4 touch

The touch command creates a file. If the file already exists, touch does not change it, but it does update the file’s modification time stamp printed with the ls -l command. For example, to create an empty file, enter this:

touch 命令用于创立文件。

如果文件曾经存在,touch 不会更改它,但会更新应用 ls - l 命令打印的文件批改工夫戳。

例如,要创立一个空文件,输出以下命令:

touch file

Then run ls -l on that file. You should see output like the following, where the date and time ➊ indicate when you ran touch:

而后在该文件上运行 ls -l。

您应该会看到相似以下的输入,其中日期和工夫 ➊ 示意您运行 touch 的工夫:

ls -l file

-rw-r--r-- 1 juser users 0 May 21 18:32➊ file

2.3.5 rm

To delete (remove) a file, use rm. After you remove a file, it’s gone from your system and generally cannot be undeleted.

要删除文件,应用 rm 命令。删除文件后,它将从零碎中隐没,通常无奈复原。

rm file

2.3.6 echo

The echo command prints its arguments to the standard output:

echo 命令将其参数打印到规范输入:

echo Hello again.
Hello again.

The echo command is very useful for finding expansions of shell globs (“wildcards”such as *) and variables (such as $HOME), which you will encounter later in this chapter.

echo 命令十分有用,能够用于查找 shell 通配符(例如 *)和变量(例如 $HOME)的扩大,您将在本章前面遇到。

2.4 Navigating Directories(目录导航)

Unix has a directory hierarchy that starts at /, sometimes called the root directory. The directory separator is the slash (/), not the backslash (). There are several standard subdirectories in the root directory, such as /usr, as you’ll learn in 2.19 Linux Directory Hierarchy Essentials.

Unix 有一个从 / 开始的目录层次结构,有时称为根目录。

目录分隔符是斜杠(/),而不是反斜杠(\)。

根目录中有几个规范子目录,例如 /usr,您将在 2.19 Linux 目录层次结构基础知识中理解到。

When you refer to a file or directory, you specify a path or pathname. When a path starts with / (such as /usr/lib), it’s a full or absolute path.

当你援用一个文件或目录时,你须要指定一个门路或路径名。

当一个门路以 / 结尾(比方 /usr/lib),它就是一个残缺的或相对的门路。

A path component identified by two dots (..) specifies the parent of a directory. For example, if you’re working in /usr/lib, the path .. would refer to /usr. Similarly, ../bin would refer to /usr/bin.

由两个点(..)标识的门路组件指定了一个目录的父目录。

例如,如果你正在 /usr/lib 中工作,门路.. 将指向 /usr。

同样,../bin 将指向 /usr/bin。

One dot (.) refers to the current directory; for example, if you’re in /usr/lib, the path . is still /usr/lib, and ./X11 is /usr/lib/X11. You won’t have to use . very often because most commands default to the current directory if a path doesn’t start with / (you could just use X11 instead of ./X11 in the preceding example).

一个点(.)示意当前目录;例如,如果你在 /usr/lib 中,门路. 依然是 /usr/lib,而./X11 是 /usr/lib/X11。

你不须要常常应用.,因为大多数命令默认应用当前目录,如果门路不以 / 结尾(在下面的例子中,你能够只应用 X11 而不是./X11)。

A path not beginning with / is called a relative path. Most of the time, you’ll work with relative pathnames, because you’ll already be in the directory you need to be in or somewhere close by.

不以 / 结尾的门路称为相对路径。

大多数状况下,你会应用相对路径名,因为你曾经在须要的目录中或者离目录很近了。

Now that you have a sense of the basic directory mechanics, here are some essential directory commands.

当初你对根本目录机制有了肯定的理解,上面是一些必要的目录命令。

2.4.1 cd

The current working directory is the directory that a process (such as the shell) is currently in. The cd command changes the shell’s current working directory:

当前工作目录是过程(比方 shell)以后所在的目录。cd 命令用于扭转 shell 的当前工作目录:

    $ cd dir

If you omit dir, the shell returns to your home directory, the directory you started in when you first logged in.

如果你省略 dir,shell 会返回你的主目录,即你首次登录时所在的目录。

2.4.2 mkdir

The mkdir command creates a new directory dir:

mkdir 命令用于创立一个新目录 dir:

$ mkdir dir

2.4.3 rmdir

The rmdir command removes the directory dir:

rmdir 命令用于删除目录 dir:

$ rmdir dir

If dir isn’t empty, this command fails. However, if you’re impatient, you probably don’t want to laboriously delete all the files and subdirectories inside dir first. You can use rm -rf dir to delete a directory and its contents, but be careful! This is one of the few commands that can do serious damage, especially if you run it as the superuser. The -r option specifies recursive delete to repeatedly delete everything inside dir, and -f forces the delete operation. Don’t use the -rf flags with globs such as a star (*). And above all, always double-check your command before you run it.

如果 dir 不为空,该命令将失败。然而,如果你不耐烦,你可能不想费劲地先删除 dir 内的所有文件和子目录。

你能够应用 rm -rf dir 命令来删除一个目录及其内容,但要小心!这是少数几个可能会造成重大侵害的命令之一,特地是如果你以超级用户身份运行它。

- r 选项指定递归删除以反复删除 dir 内的所有内容,- f 强制执行删除操作。

不要在带有通配符(比方星号 *)的状况下应用 -rf 标记。

最重要的是,在运行命令之前始终仔细检查命令。

2.4.4 Shell Globbing(通配符)

The shell can match simple patterns to file and directory names, a process known as globbing. This is similar to the concept of wildcards in other systems. The simplest of these is the glob character *, which tells the shell to match any number of arbitrary characters. For example, the following command prints a list of files in the current directory:

shell 能够将简略的模式与文件和目录名匹配,这个过程称为 globbing。

这相似于其余零碎中通配符的概念。其中最简略的是通配符 *,它通知 shell 匹配任意数量的任意字符。

例如,以下命令打印出当前目录中的文件列表:

$ echo *

The shell matches arguments containing globs to filenames, substitutes the filenames for those arguments, and then runs the revised command line. The substitution is called expansion because the shell substitutes all matching filenames. Here are some ways to use * to expand filenames:

shell 将匹配蕴含通配符的参数与文件名,用文件名替换这些参数,而后运行批改后的命令行。

这个替换被称为扩大,因为 shell 会替换所有匹配的文件名。

上面是一些应用 * 扩大文件名的办法:

o at* expands to all filenames that start with at.
o *at expands to all filenames that end with at.
o at expands to all filenames that contain at.

  • at* 扩大到以 at 结尾的所有文件名。
  • *at 扩大到以 at 结尾的所有文件名。*
  • at* 扩大到蕴含 at 的所有文件名。

If no files match a glob, the shell performs no expansion, and the command runs with literal characters such as . For example, try a command such as echo dfkdsafh.

如果没有文件与通配符匹配,shell 不进行扩大,命令将以字面字符运行,比方 *。例如,尝试执行像echo *dfkdsafh 这样的命令。

NOTE If you’re used to MS-DOS, you might instinctively type . to match all files. Break this habit now. In Linux and other versions of Unix, you must use to match all files. In the Unix shell, .* matches only files and directories that contain the dot (.) character in their names. Unix filenames do not need extensions and often do not carry them.

留神

如果你习惯于 MS-DOS,你可能本能地输出 *.* 来匹配所有文件。当初要突破这个习惯。

在 Linux 和其余版本的 Unix 中,你必须应用 * 来匹配所有文件。在 Unix shell 中,*.*只匹配文件名和目录名中蕴含点(.)字符的文件和目录。

Unix 文件名不须要扩展名,而且通常不带有扩展名。

Another shell glob character, the question mark (?), instructs the shell to match exactly one arbitrary character. For example, b?at matches boat and brat.

另一个 shell 通配符,问号(?),批示 shell 匹配一个任意字符。

例如,b?at 匹配 boat 和 brat。

If you don’t want the shell to expand a glob in a command, enclose the glob in single quotes (”). For example, the command echo ‘*’ prints a star. You will find this handy for a few of the commands described in the next section, such as grep and find. (You’ll learn more much about quoting in 11.2 Quoting and Literals.)

如果你不心愿 shell 在命令中扩大通配符,将通配符括在单引号(”)中。

例如,命令 echo ‘*’ 打印一个星号。

对于下一节中形容的一些命令,如 grep 和 find,你会发现这很不便。

(你将在 11.2 援用和字面值中理解更多对于援用的内容。)

NOTE It is important to remember that the shell performs expansions before running commands, and only then. Therefore, if a * makes it to a command without expanding, the shell will do nothing more with it; it’s up to the command to decide what it wants to do.
留神 必须记住,shell 在运行命令之前会执行扩大,而且仅在执行命令时才会这样做。因而,如果 * 进入命令后没有进行扩大,shell 就不会再对它做任何事件,而是由命令本人决定要做什么。

There is more to a modern shell’s pattern-matching capabilities, but * and ? are what you need to know now.

古代 shell 的模式匹配性能还有很多,但 * 和 ? 是你当初须要晓得的。

2.5 Intermediate Commands(中级命令)

The following sections describe the most essential intermediate Unix commands.

以下局部介绍了最根本的中级 Unix 命令。

2.5.1 grep

The grep command prints the lines from a file or input stream that match an expression. For example, to print the lines in the /etc/passwd file that contain the text root, enter this:

grep 命令会打印出与表达式匹配的文件或输出流中的行。

例如,要打印出蕴含文本 ”root” 的 /etc/passwd 文件中的行,请输出以下命令:


$ grep root /etc/passwd

The grep command is extraordinarily handy when operating on multiple files at once because it prints the filename in addition to the matching line. For example, if you want to check every file in /etc that contains the word root, you could use this command:

grep 命令在同时操作多个文件时十分不便,因为它除了打印匹配的行外,还会打印出文件名。

例如,如果你想查看 /etc 目录中蕴含单词 ”root” 的所有文件,能够应用以下命令:

$ grep root /etc/*

Two of the most important grep options are -i (for case-insensitive matches) and -v (which inverts the search, that is, prints all lines that don’t match). There is also a more powerful variant called egrep (which is just a synonym for grep -E).

grep 命令的两个最重要的选项是 -i(用于疏忽大小写)和 -v(反转搜寻,即打印出所有不匹配的行)。还有一个更弱小的变体叫做 egrep(它只是 grep - E 的同义词)。

grep understands patterns known as regular expressions that are grounded in computer science theory and are very common in Unix utilities. Regular expressions are more powerful than wildcard-style patterns, and they have a different syntax. There are two important things to remember about regular expressions:

grep 了解称为正则表达式的模式,这些模式扎根于计算机科学实践,并且在 Unix 实用工具中十分常见。正则表达式比通配符款式更弱小,语法也有所不同。对于正则表达式,有两个重要的事件须要记住:

o . matches any number of characters (like the in wildcards).
o . matches one arbitrary character.

o .匹配任意数量的字符(相似于通配符中的)。
o . 匹配一个任意字符。

NOTE The grep(1) manual page contains a detailed description of regular expressions, but it can be a little difficult to read. To learn more, you can read Mastering Regular Expressions, 3rd edition (O’Reilly, 2006), or see the regular expressions chapter of Programming Perl, 4th edition (O’Reilly, 2012). If you like math and are interested in where regular expressions come from, look up Introduction to Automata Theory, Languages, and Computation, 3rd edition (Prentice Hall, 2006).

留神

grep(1)的手册页面蕴含了对正则表达式的详细描述,但浏览起来可能有些艰难。

如果想理解更多,能够浏览《精通正则表达式》第 3 版(O’Reilly,2006),或者查看《Perl 编程》第 4 版(O’Reilly,2012)中的正则表达式章节。

如果你喜爱数学,并且对正则表达式的起源感兴趣,请查阅《自动机实践、语言和计算导论》第 3 版(Prentice Hall,2006)。

2.5.2 less

The less command comes in handy when a file is really big or when a command’s output is long and scrolls off the top of the screen.

当文件十分大或者命令的输入内容很长并且超出屏幕时,less 命令十分有用。

To page through a big file like /usr/share/dict/words, use the command less /usr/share/dict/words. When running less, you’ll see the contents of the file one screenful at a time. Press the spacebar to go forward in the file and the b key to skip back one screenful. To quit, type q

要浏览像 /usr/share/dict/words 这样的大文件,能够应用命令 less /usr/share/dict/words。运行 less 时,你会一次看到文件的一页内容。按下空格键向前翻页,按下 b 键向后翻页。要退出,输出 q。

NOTE The less command is an enhanced version of an older program named more. Most Linux desktops and servers have less, but it’s not standard on many embedded systems and other Unix systems. So if you ever run into a situation when you can’t use less, try more

留神

less 命令是一个改良版本的旧程序 more。大多数 Linux 桌面和服务器都有 less,但在许多嵌入式零碎和其余 Unix 零碎中并不规范。所以,如果你遇到无奈应用 less 的状况,请尝试应用 more。

You can also search for text inside less. For example, to search forward for a word, type /word, and to search backward, use ?word. When you find a match, press n to continue searching.

你还能够在 less 中搜寻文本。例如,要向前搜寻一个单词,输出 /word,要向后搜寻,应用?word。当找到匹配项时,按下 n 键持续搜寻。

As you’ll learn in 2.14 Shell Input and Output, you can send the standard output of nearly any program directly to another program’s standard input. This is exceptionally useful when you have a command with a lot of output to sift through and you’d like to use something like less to view the output. Here’s an example of sending the output of a grep command to less:

正如你将在 2.14 Shell 输出和输入中学到的那样,你能够将简直任何程序的规范输入间接发送到另一个程序的规范输出。

当你有一个有大量输入须要筛选的命令,并且想要应用相似 less 的工具查看输入时,这十分有用。上面是一个将 grep 命令的输入发送到 less 的示例:

$ grep ie /usr/share/dict/words | less

Try this command out for yourself. You’ll probably use less like this a lot.

请本人尝试一下这个命令。你可能常常会这样应用 less。

2.5.3 pwd

The pwd (print working directory) program simply outputs the name of the current working directory. You may be wondering why you need this when most Linux distributions set up accounts with the current working directory in the prompt. There are two reasons.

pwd(打印当前工作目录)程序简略地输入当前工作目录的名称。你可能会想晓得为什么须要这个,因为大多数 Linux 发行版在提示符中设置了当前工作目录。有两个起因。

First, not all prompts include the current working directory, and you may even want to get rid of it in your own prompt because it takes up a lot of space. If you do so, you need pwd.

首先,并不是所有的提示符都蕴含当前工作目录,你甚至可能想要在本人的提示符中去掉它,因为它占用了很多空间。如果这样做,你就须要 pwd。

Second, the symbolic links that you’ll learn about in 2.17.2 Symbolic Links can sometimes obscure the true full path of the current working directory. You’ll use pwd -P to eliminate this confusion.

其次,在 2.17.2 符号链接中学到的符号链接有时可能会暗藏当前工作目录的实在残缺门路。你将应用 pwd - P 来打消这种混同。

2.5.4 diff

To see the differences between two text files, use diff:

要查看两个文本文件之间的差别,应用 diff 命令:


$ diff file1 file2

Several options can control the format of the output, and the default output format is often the most comprehensible for human beings. However, most programmers prefer the output from diff -u when they need to send the output to someone else because automated tools can make better use of it.

有几个选项能够管制输入的格局,而默认输入格局通常对人类来说是最易了解的。

然而,大多数程序员在须要将输入发送给别人时更喜爱 diff - u 的输入,因为自动化工具能够更好地利用它。

2.5.5 file

If you see a file and are unsure of its format, try using the file command to see if the system can guess:

如果你看到一个文件并且不确定它的格局,能够尝试应用 file 命令查看零碎是否可能猜想:


$ file file

You may be surprised by how much this innocent-looking command can do.

你可能会对这个看似有害的命令能做多少事件感到诧异。

2.5.6 查找和定位

It’s frustrating when you know that a certain file is in a directory tree somewhere but you just don’t know where. Run find to find file in dir:

当你晓得某个文件在某个目录树中,然而却不晓得具体位置时,这真是令人丧气。应用 find 命令在目录中查找文件:

$ find dir -name file -print

Like most programs in this section, find is capable of some fancy stuff. However, don’t try options such as -exec before you know the form shown here by heart and why you need the -name and -print options. The find command accepts special pattern-matching characters such as , but you must enclose them in single quotes (‘‘)to protect the special characters from the shell’s own globbing feature. (Recall from 2.4.4 Shell Globbing (Wildcards) that the shell expands globs before running commands.)

和本节中的大多数程序一样,find 命令也能够实现一些花哨的操作。

然而,在你齐全把握并了解这里所展现的模式以及为什么须要应用 -name 和 -print 选项之前,不要尝试像 -exec 这样的选项。

find 命令承受非凡的模式匹配字符,比方 *,然而你必须应用单引号 (”) 将它们括起来,以爱护这些特殊字符免受 shell 本身的通配符扩大的影响。

(回顾一下 2.4.4 节中介绍的 Shell 通配符,即 shell 在运行命令之前会扩大通配符。)

Most systems also have a locate command for finding files. Rather than searching for a file in real time, locate searches an index that the system builds periodically. Searching with locate is much faster than find, but if the file you’re looking for is newer than the index, locate won’t find it.

大多数零碎还提供了一个 locate 命令用于查找文件。

与实时搜寻文件不同,locate 命令搜寻的是零碎定期构建的索引。

应用 locate 进行搜寻比应用 find 快得多,然而如果你要查找的文件比索引更新,locate 将无奈找到它。

2.5.7 head 和 tail

To quickly view a portion of a file or stream of data, use the head and tail commands. For example, head /etc/passwd shows the first 10 lines of the password file, and tail /etc/passwd shows the last 10 lines.

要疾速查看文件或数据流的一部分,能够应用 head 和 tail 命令。

例如,head /etc/passwd 显示密码文件的前 10 行,而 tail /etc/passwd 显示最初 10 行。

要更改要显示的行数,应用 - n 选项,其中 n 是你想要查看的行数(例如,head -5 /etc/passwd)。要打印从第 n 行开始的行,应用 tail +n。

2.5.8 sort


The sort command quickly puts the lines of a text file in alphanumeric order. If the file’s lines start with numbers and you want to sort in numerical order, use the -n option. The -r option reverses the order of the sort.

sort 命令能够疾速将文本文件的行按字母数字程序排序。

如果文件的行以数字结尾,并且你想按数字程序排序,应用 - n 选项。- r 选项能够反转排序的程序。

2.6 Changing Your Password and Shell(批改明码和 Shell)

Use the passwd command to change your password. You’ll be asked for your old password and then prompted for your new password twice. Choose a password that does not include real words in any language and don’t try to combine words.

应用 passwd 命令来批改明码。你将会被要求输出旧明码,而后再输出新密码两次。抉择一个不蕴含任何语言中的实在单词,并且不尝试组合单词的明码。

One of the easiest ways to create a good password is to pick a sentence, produce an acronym from it, and then modify the acronym with a number or some punctuation. Then all you need to do is remember the sentence.

创立一个好的明码的最简略办法之一是抉择一个句子,从中产生一个首字母缩写,而后用数字或标点符号批改这个缩写。而后你只须要记住这个句子。

You can change your shell with the chsh command (to an alternative such as ksh or tcsh), but keep in mind that this book assumes that you’re running bash

你能够应用 chsh 命令来更改你的 Shell(例如 ksh 或 tcsh),但请记住,本书假如你正在运行 bash。

2.7 Dot Files(点文件)

Change to your home directory, take a look around with ls, and then run ls -a. Do you see the difference in the output? When you run ls without the -a, you won’t see the configuration files called dot files. These are files and directories whose names begin with a dot (.). Common dot files are .bashrc and .login, and there are dot directories, too, such as .ssh.

切换到你的主目录,用 ls 命令查看一下,而后运行 ls -a。

你看到输入的差别了吗?当你运行 ls 而不带上 - a 选项时,你看不到被称为点文件的配置文件。

这些是以点(.)结尾的文件和目录。

常见的点文件有.bashrc 和.login,还有点目录,比方.ssh。

There is nothing special about dot files or directories. Some programs don’t show them by default so that you won’t see a complete mess when listing the contents of your home directory. For example, ls doesn’t list dot files unless you use the -a option. In addition, shell globs don’t match dot files unless you explicitly use a pattern such as .*.

点文件或目录并没有什么特别之处。

有些程序默认不显示它们,这样当列出主目录的内容时,你不会看到一团糟。

例如,ls 命令不会列出点文件,除非你应用了 - a 选项。

此外,Shell 通配符不会匹配点文件,除非你明确应用模式,比方.*。

NOTE You can run into problems with globs because . matches . and .. (the current and parent directories). You may wish to use a pattern such as .1 or .??* to get all dot files except the current and parent directories.

留神

通配符可能会导致问题,因为.* 会匹配. 和..(当前目录和父目录)。

你可能心愿应用相似.1或.??的模式来获取除当前目录和父目录之外的所有点文件。

2.8 Environment and Shell Variables(环境和 Shell 变量)

The shell can store temporary variables, called shell variables, containing the values of text strings. Shell variables are very useful for keeping track of values in scripts, and some shell variables control the way the shell behaves. (For example, the bash shell reads the PS1 variable before displaying the prompt.)

Shell 能够存储长期变量,称为 Shell 变量,其中蕴含文本字符串的值。

Shell 变量在脚本中跟踪值十分有用,而且一些 Shell 变量能够管制 Shell 的行为形式(例如,bash Shell 在显示提示符之前会读取 PS1 变量)。

To assign a value to a shell variable, use the equal sign (=). Here’s a simple example:

要给 Shell 变量赋值,应用等号(=)。上面是一个简略的示例:

$ STUFF=blah

下面的示例将名为 STUFF 的变量的值设置为 blah。要拜访这个变量,应用 $STUFF(例如,尝试运行 echo $STUFF)。你将在第 11 章中理解到 Shell 变量的许多用处。

环境变量相似于 Shell 变量,但它不是特定于 Shell。Unix 零碎上的所有过程都有环境变量存储空间。环境变量和 Shell 变量的次要区别在于,操作系统将你的 Shell 的所有环境变量传递给 Shell 运行的程序,而 Shell 变量无奈在你运行的命令中拜访。

应用 Shell 的 export 命令来调配一个环境变量。例如,如果你想将 $STUFF Shell 变量变成环境变量,应用以下命令:

$ STUFF=blah
$ export STUFF

环境变量十分有用,因为许多程序会读取它们来进行配置和选项。例如,你能够将你最喜爱的 less 命令行选项放在 LESS 环境变量中,当你运行 less 时,它将应用这些选项。(许多手册页蕴含一个标记为 ENVIRONMENT 的局部,形容了这些变量。)

2.9 The Command Path(命令门路)

PATH 是一个非凡的环境变量,它蕴含了命令门路(或简称为门路)。命令门路是一个系统目录的列表,当 shell 尝试定位一个命令时,它会在这些目录中进行搜寻。例如,当你运行 ls 命令时,shell 会在 PATH 列出的目录中搜寻 ls 程序。如果门路中的多个目录中都有同名的程序,shell 会运行第一个匹配的程序。
如果你运行 echo $PATH 命令,你会看到门路的组成部分是由冒号 (:) 分隔的。例如:
$ echo $PATH
/usr/local/bin:/usr/bin:/bin
要通知 shell 在更多中央寻找程序,能够批改 PATH 环境变量。例如,通过应用这个命令,你能够将目录 dir 增加到门路的结尾,这样 shell 会在 dir 中查找程序,而不是在其余 PATH 目录中查找。
$ PATH=dir:$PATH
或者你能够将一个目录名追加到 PATH 变量的开端,这会导致 shell 最初在 dir 中查找:
$ PATH=$PATH:dir
留神
批改门路时要小心,因为如果你谬误地输出了 $PATH,可能会意外清空整个门路。如果产生这种状况,不要惊恐!损坏并不是永恒的;你能够重新启动一个新的 shell。(要实现长久成果,你须要在编辑某个配置文件时谬误地输出,即使如此,也很容易纠正。)返回失常状态的最简略办法之一是敞开以后的终端窗口并启动另一个窗口。

2.10 Special Characters(特殊字符)

When discussing Linux with others, you should know a few names for some of the special characters that you’ll encounter. If you’re amused by this sort of thing, see the“Jargon File”(http://www.catb.org/jargon/html/) or its printed companion, The New Hacker’s Dictionary (MIT Press, 1996). Table 2-1 describes a select set of the special characters, many of which you’ve already seen in this chapter. Some utilities, such as the Perl programming language, use almost all of these special characters! (Keep in mind that these are the American names for the characters.)

当与别人探讨 Linux 时,你应该理解一些特殊字符的名称,因为你会遇到它们。

如果你对这类事件感到乏味,能够参考《术语文件》(http://www.catb.org/jargon/html/)或其印刷版《新黑客词典》(MIT 出版社,1996 年)。

表 2 - 1 形容了一些特殊字符的抉择集,其中许多你在本章中曾经见过。

一些工具,如 Perl 编程语言,简直应用了所有这些特殊字符!(请记住,这些是这些字符的美国名称。)

Table 2-1. Special Characters

Table 2-1. Special Characters

You will often see control characters marked with a caret; for example, ^C for ctrl-c.

您常常会看到用圆点标记的控制字符,例如,^C 示意 ctrl-c。

2.11 Command-Line Editing(命令行编辑)

As you play with the shell, notice that you can edit the command line using the left and right arrow keys, as well as page through previous commands using the up and down arrows. This is standard on most Linux systems.

当你应用 shell 时,你会留神到你能够应用左右箭头键来编辑命令行,还能够应用高低箭头键浏览之前的命令。

这在大多数 Linux 零碎上都是规范的。

However, it’s a good idea to forget about the arrow keys and use control key sequences instead. If you learn the ones listed in Table 2-2, you’ll find that you’re better able to enter text in the many Unix programs that use these standard keystrokes.

然而,最好忘掉箭头键,而是应用控制键序列。

如果你学会了表 2 - 2 中列出的控制键序列,你会发现你能更好地在许多应用这些规范按键的 Unix 程序中输出文本。

Table 2-2. Command-Line Keystrokes

2.12 Text Editors(文本编辑器)

Speaking of editing, it’s time to learn an editor. To get serious with Unix, you must be able to edit text files without damaging them. Most parts of the system use plaintext configuration files (like the ones in /etc). It’s not difficult to edit files, but you will do it so often that you need a powerful tool for the job.

说到编辑,当初是时候学习一个编辑器了。

要认真对待 Unix,你必须可能在不损坏文件的状况下编辑文本文件。

零碎的大部分局部应用纯文本配置文件(比方在 /etc 目录下的文件)。

编辑文件并不艰难,但你会常常这样做,所以须要一个弱小的工具来实现这项工作。

You should try to learn one of the two de facto standard Unix text editors, vi and Emacs. Most Unix wizards are religious about their choice of editor, but don’t listen to them. Just choose for yourself. If you choose one that matches the way that you work, you’ll find it easier to learn. Basically, the choice comes down to this:

你应该尝试学习两个事实上的规范 Unix 文本编辑器之一,vi 和 Emacs。

大多数 Unix 专家对于他们抉择的编辑器都有宗教般的酷爱,但不要听他们的。

只需抉择适宜本人工作形式的编辑器即可,这样你会发现学习起来更容易。

基本上,抉择编辑器有以下几点:

o If you want an editor that can do almost anything and has extensive online help, and you don’t mind doing ome extra typing to get these features, try Emacs.
o If speed is everything, give vi a shot; it“plays”a bit like a video game.

  • 如果你想要一个简直能够做任何事件并且有宽泛在线帮忙的编辑器,而且不介意为了应用这些性能而多输出一些命令,能够尝试 Emacs。
  • 如果速度至关重要,能够试试 vi;它的应用形式有点像玩电子游戏。

Learning the vi and Vim Editors: Unix Text Processing, 7th edition (O’Reilly, 2008) can tell you everything you need to know about vi. For Emacs, use the online tutorial: Start Emacs, press CTRL-H, and then type T. Or read GNU Emacs Manual (Free Software Foundation, 2011).

《学习 vi 和 Vim 编辑器:Unix 文本处理,第 7 版》(O’Reilly,2008)能够通知你对于 vi 的所有。

对于 Emacs,能够应用在线教程:启动 Emacs,按下 CTRL-H,而后输出 T。

或者浏览《GNU Emacs 手册》(自由软件基金会,2011)。

You might be tempted to experiment with a friendlier editor when you first start out, such as Pico or one of the myriad GUI editors out there, but if you tend to make a habit out of the first thing that you use, you don’t want to go down this route.

当你刚开始时,可能会尝试应用一个更敌对的编辑器,比方 Pico 或者其余各种图形界面编辑器,但如果你偏向于养成第一次应用的习惯,就不要走这条路。

NOTE Editing text is where you’ll first start to see a difference between the terminal and the GUI. Editors such as vi run inside the terminal window, using the standard terminal I/O interface. GUI editors start their own window and present their own interface, independent of terminals. Emacs runs in a GUI by default but will run in a terminal window as well.

留神

编辑文本是你首次开始看到终端和图形界面之间差别的中央。

例如 vi 这样的编辑器在终端窗口内运行,应用规范终端 I / O 接口。

图形界面编辑器则启动本人的窗口,并出现独立于终端的界面。

Emacs 默认在图形界面中运行,但也能够在终端窗口中运行。

2.13 Getting Online Help(获取在线帮忙)

Linux systems come with a wealth of documentation. For basic commands, the manual pages (or man pages) will tell you what you need to know. For example, to see the manual page for the ls command, run man as follows:

Linux 零碎提供了丰盛的文档资源。对于根本命令,手册页(或 man 页)会告诉您所需的信息。

例如,要查看 ls 命令的手册页,请运行以下命令:

$ man ls

Most manual pages concentrate primarily on reference information, perhaps with some examples and crossreferences, but that’s about it. Don’t expect a tutorial, and don’t expect an engaging literary style

大多数手册页次要集中在参考信息上,可能会蕴含一些示例和穿插援用,但仅此而已。

不要冀望有教程,也不要冀望有引人入胜的文学格调。

When programs have many options, the manual page often lists the options in some systematic way (for example, in alphabetical order), but it won’t tell you what the important ones are. If you’re patient, you can usually find what you need to know in the man page. If you’re impatient, ask a friend—or pay someone to be your friend so that you can ask him or her.

当程序有许多选项时,手册页通常会以某种零碎的形式列出这些选项(例如按字母程序),但它不会告诉您哪些是重要的选项。

如果您急躁一点,通常能够在手册页中找到所需的信息。

如果您不耐烦,能够向敌人询问,或者付钱请人充当您的敌人,这样您就能够向他们发问。

To search for a manual page by keyword, use the -k option:

要按关键字搜寻手册页,请应用 - k 选项:

$ man -k keyword

This is helpful if you don’t quite know the name of the command that you want. For example, if you’re looking for a command to sort something, run:

如果您不太晓得所需命令的名称,这将很有帮忙。例如,如果您正在寻找一个用于排序的命令,请运行:

$ man -k sort
--snip--
comm (1) - compare two sorted files line by line
qsort (3) - sorts an array
sort (1) - sort lines of text files
sortm (1) - sort messages
tsort (1) - perform topological sort
--snip--

The output includes the manual page name, the manual section (see below), and a quick description of what the manual page contains.

输入后果包含手册页面名称、手册局部(见下文)以及手册页面内容的疾速形容。

NOTE

If you have any questions about the commands described in the previous sections, you may be able to find the answers by using the man command.

留神

如果您对后面章节中形容的命令有任何疑难,能够应用 man 命令找到答案。

Manual pages are referenced by numbered sections. When someone refers to a manual page, the section number appears in parentheses next to the name, like ping(8), for example. Table 2-3 lists the sections and their numbers.

手册页面按章节编号援用。当有人援用手册页面时,章节编号会呈现在名称旁边的括号中,例如 ping(8)。表 2-3 列出了章节及其编号。

Table 2-3. Online Manual Sections

表 2-3. 联机手册章节

Sections 1, 5, 7, and 8 should be good supplements to this book. Section 4 may be of marginal use, and Section 6 would be great if only it were a little larger. You probably won’t be able to use Section 3 if you aren’t a programmer, but you may be able to understand some of the material in Section 2 once you’ve read more about system calls in this book.

第 1、5、7 和 8 节应该是这本书的很好的补充。第 4 节可能有一些边缘用处,如果第 6 节能再大一点就更好了。

如果你不是程序员,可能无奈应用第 3 节,然而在浏览本书对于零碎调用的更多内容后,你可能可能了解第 2 节的一些资料。

You can select a manual page by section, which is sometimes important because man displays the first manual page that it finds when matching a particular search term. For example, to read the /etc/passwd file description (as opposed to the passwd command), you can insert the section number before the page name:

您能够按节抉择手册页,这有时很重要,因为当匹配特定搜索词时,man 会显示它找到的第一个手册页。

例如,要浏览 /etc/passwd 文件的形容(而不是 passwd 命令),您能够在页面名称之前插入节号:

$ man 5 passwd

Manual pages cover the essentials, but there are many more ways to get online help. If you’re just looking for a certain option for a command, try entering a command name followed by –help or -h (the option varies from command to command). You may get a deluge (as in the case of ls –help), or you may find just what you’re looking for

手册页涵盖了根本内容,但还有许多其余获取在线帮忙的办法。

如果您只是想要某个命令的特定选项,请尝试输出命令名称后跟 –help 或 -h(选项因命令而异)。

您可能会失去一大堆信息(例如 ls –help 的状况),或者您可能只找到您须要的内容。

Some time ago, the GNU Project decided that it didn’t like manual pages very much and switched to another format called info (or texinfo). Often this documentation goes further than a typical manual page does, but it is sometimes more complex. To access an info manual, use info with the command name:

一段时间以前,GNU 我的项目决定不太喜爱手册页,而是转向另一种称为 info(或 texinfo)的格局。

通常,这种文档比典型的手册页更具体,但有时更简单。

要拜访 info 手册,请应用 info 和命令名称:

$ info command

Some packages dump their available documentation into /usr/share/doc with no regard for online manual systems such as man or info. See this directory on your system if you find yourself searching for documentation. And of course, search the Internet.

一些软件包会将其可用的文档转储到 /usr/share/doc 中,而不思考 man 或 info 等在线手册零碎。

如果您发现自己在搜寻文档,请查看您零碎上的此目录。

当然,还能够在互联网上搜寻。

2.14 Shell Input and Output(Shell 输出和输入)

Now that you’re familiar with basic Unix commands, files, and directories, you’re ready to learn how to redirect standard input and output. Let’s start with standard output.

当初你曾经相熟了根本的 Unix 命令、文件和目录,你能够学习如何重定向规范输出和输入了。咱们先从规范输入开始。

To send the output of command to a file instead of the terminal, use the > redirection character:

要将命令的输入发送到文件而不是终端,请应用重定向字符 >:

$ command > file

The shell creates file if it does not already exist. If file exists, the shell erases (clobbers) the original file first. (Some shells have parameters that prevent clobbering. For example, enter set -C to avoid clobbering in bash.)

如果文件不存在,shell 会创立该文件。

如果文件曾经存在,shell 会先擦除(笼罩)原文件。(一些 shell 有参数能够避免擦除。

例如,在 bash 中输出 set - C 能够防止擦除。)

你也能够应用 >> 重定向语法将输入追加到文件中而不是笼罩它:

$ command >> file

This is a handy way to collect output in one place when executing sequences of related commands.

这是在执行相干命令序列时,将输入收集到一个中央的便捷形式。

To send the standard output of a command to the standard input of another command, use the pipe character (|). To see how this works, try these two commands:

要将一个命令的规范输入发送到另一个命令的规范输出,应用管道符号 |。

试试上面这两个命令,看看它们是如何工作的:

$ head /proc/cpuinfo
$ head /proc/cpuinfo | tr a-z A-Z

You can send output through as many piped commands as you wish; just add another pipe before each additional command.

你能够通过任意多个管道命令发送输入,只需在每个附加命令之前增加另一个管道符号。

2.14.1 Standard Error(规范谬误)

Occasionally, you may redirect standard output but find that the program still prints something to the terminal. This is called standard error (stderr); it’s an additional output stream for diagnostics and debugging.

有时,你可能重定向了规范输入,但发现程序依然在终端打印一些内容。

这被称为规范谬误(stderr),它是用于诊断和调试的额定输入流。

For example, this command produces an error:

例如,上面的命令会产生一个谬误:

$ ls /fffffffff > f

After completion, f should be empty, but you still see the following error message on the terminal as standard error:

实现后,f 应该是空的,但你依然会在终端上看到以下规范谬误的谬误音讯:

ls: cannot access /fffffffff: No such file or directory

You can redirect the standard error if you like. For example, to send standard output to f and standard error to e, use the 2> syntax, like this:

你能够重定向规范谬误。例如,要将规范输入发送到 f,将规范谬误发送到 e,能够应用 2> 语法,像这样:

$ ls /fffffffff > f 2> e

The number 2 specifies the stream ID that the shell modifies. Stream ID 1 is standard output (the default), and 2 is standard error.

数字 2 指定了 shell 批改的流 ID。流 ID 1 是规范输入(默认值),2 是规范谬误。

You can also send the standard error to the same place as stdout with the >& notation. For example, to send both standard output and standard error to the file named f, try this command:

你也能够应用 >& 符号将规范谬误发送到与 stdout 雷同的地位。例如,要将规范输入和规范谬误都发送到名为 f 的文件中,能够尝试以下命令:

$ ls /fffffffff > f 2>&1

2.14.2 Standard Input Redirection(规范输出重定向)

To channel a file to a program’s standard input, use the < operator:

要将文件传递给程序的规范输出,请应用 < 运算符:

$ head < /proc/cpuinfo

You will occasionally run into a program that requires this type of redirection, but because most Unix commands accept filenames as arguments, this isn’t very common. For example, the preceding command could have been written as head /proc/cpuinfo.

偶然会遇到须要这种类型重定向的程序,但因为大多数 Unix 命令承受文件名作为参数,所以这种状况并不常见。

例如,后面的命令也能够写成 head /proc/cpuinfo。

2.15 Understanding Error Messages(了解谬误音讯)

When you encounter a problem on a Unix-like system such as Linux, you must read the error message. Unlike messages from other operating systems, Unix errors usually tell you exactly what went wrong.

在类 Unix 零碎(如 Linux)上遇到问题时,必须浏览谬误音讯。与其余操作系统的音讯不同,Unix 的谬误音讯通常会精确通知你出了什么问题。

2.15.1 UNIX 谬误音讯的组成

Most Unix programs generate and report the same basic error messages, but there can be subtle differences between the output of any two programs. Here’s an example that you’ll certainly encounter in some form or other:

大多数 Unix 程序生成并报告雷同的根本谬误音讯,但两个程序的输入之间可能存在细微差别。以下是一个你必定会以某种模式遇到的示例:

$ ls /dsafsda 
ls: cannot access /dsafsda: No such file or directory 

There are three components to this message:

这个音讯蕴含三个组成部分:

o The program name, ls. Some programs omit this identifying information, which can be annoying when writing shell scripts, but it’s not really a big deal.
o The filename, /dsafsda, which is a more specific piece of information. There’s a problem with this path.
o The error No such file or directory indicates the problem with the filename.

o 程序名称 ls。一些程序会省略这个标识信息,在编写 shell 脚本时可能会有些烦人,但这并不是什么大问题。
o 文件名 /dsafsda,它是一个更具体的信息。这个门路有问题。
o 谬误音讯 “ 没有那个文件或目录 ” 批示了文件名的问题。

Putting it all together, you get something like“ls tried to open /dsafsda but couldn’t because it doesn’t exist.”This may seem obvious, but these messages can get a little confusing when you run a shell script that includes an erroneous command under a different name.

综合起来,你会失去相似于 “ls 试图关上 /dsafsda,但因为它不存在,所以无奈关上 ” 的信息。这仿佛很显著,但当你在以不同的名称运行一个蕴含谬误命令的 shell 脚本时,这些音讯可能会有点令人困惑。

When troubleshooting errors, always address the first error first. Some programs report that they can’t do anything before reporting a host of other problems. For example, say you run a fictitious program called scumd and you see this error message:

在排除谬误时,始终首先解决第一个谬误。有些程序在报告一系列其余问题之前可能会报告无奈执行任何操作的谬误。例如,假如你运行一个名为 scumd 的虚构程序,并看到以下谬误音讯:

scumd: cannot access /etc/scumd/config: No such file or directory

Following this is a huge list of other error messages that looks like a complete catastrophe. Don’t let those other errors distract you. You probably just need to create /etc/scumd/config.

接下来是一个微小的谬误音讯列表,看起来像是一场齐全的劫难。不要让这些其余谬误扩散你的注意力。你可能只须要创立 /etc/scumd/config。

NOTE Don’t confuse error messages with warning messages. Warnings often look like errors, but they contain the word warning. A warning usually means something is wrong but the program will try to continue running anyway. To fix a problem noted in a warning message, you may have to hunt down a process and kill it before doing anything else. (You’ll learn about listing and killing processes in 2.16 Listing and Manipulating Processes.)

留神:

不要将谬误音讯与正告音讯混同。正告通常看起来像谬误,但它们蕴含了 ” 正告 ” 一词。

正告通常意味着有些问题,但程序将尝试持续运行。

要修复正告音讯中指出的问题,你可能须要在执行其余操作之前查找并终止一个过程(你将在 2.16 列出和操作过程中学习如何列出和终止过程)。

2.15.2 Common Errors(常见谬误)

Many errors that you’ll encounter in Unix programs result from things that can go wrong with files and processes. Here’s an error message hit parade:

在 Unix 程序中,许多谬误是因为文件和过程呈现问题导致的。以下是一些常见的错误信息:

No such file or directory(没有这个文件或目录)

This is the number one error. You tried to access a file that doesn’t exist. Because the Unix file I/O system doesn’t discriminate between files and directories, this error message occurs everywhere. You get it when you try to read a file that does not exist, when you try to change to a directory that isn’t there, when you try to write to a file in a directory that doesn’t exist, and so on.

这是最常见的谬误。您尝试拜访一个不存在的文件。因为 Unix 文件 I / O 系统对文件和目录没有区别,所以这个错误信息无处不在。当您尝试读取一个不存在的文件、切换到一个不存在的目录、向一个不存在的目录中的文件写入时,都会呈现这个错误信息。

File exists(文件已存在)

In this case, you probably tried to create a file that already exists. This is common when you try to create a directory with the same name as a file.

在这种状况下,您可能尝试创立一个曾经存在的文件。当您尝试以与文件同名的形式创立一个目录时,这种状况很常见。

Not a directory, Is a directory 不是一个目录,是一个目录

These messages pop up when you try to use a file as a directory or a directory as a file. For example:

当您尝试将文件用作目录或将目录用作文件时,这些音讯会弹出。例如:

$ touch a 
$ touch a/b 
touch: a/b: Not a directory 

Notice that the error message only applies to the a part of a/b. When you encounter this problem, you may need to dig around a little to find the path component that is being treated like a directory.

请留神,谬误音讯仅实用于 a / b 中的 a 局部。当遇到此问题时,您可能须要认真查找被视为目录的门路组件。

No space left on device 设施上没有残余空间

You’re out of disk space.

您的磁盘空间已用完。

Permission denied(权限被回绝)

You get this error when you attempt to read or write to a file or directory that you’re not allowed to access (you have insufficient privileges). This error also shows when you try to execute a file that does not have the execute bit set (even if you can read the file). You’ll read more about permissions in 2.17 File Modes and Permissions.

当您尝试读取或写入一个您没有权限拜访的文件或目录时,会呈现此谬误(权限有余)。当您尝试执行一个没有设置执行位的文件时(即便您能够读取该文件),也会显示此谬误。您将在 2.17 文件模式和权限中理解更多对于权限的内容。

Operation not permitted(操作不容许)

This usually happens when you try to kill a process that you don’t own.

通常在您尝试终止一个您不领有的过程时会产生这种状况

Segmentation fault, Bus error(分段谬误,总线谬误)

A segmentation fault essentially means that the person who wrote the program that you just ran screwed up somewhere. The program tried to access a part of memory that it was not allowed to touch, and the operating system killed it. Similarly, a bus error means that the program tried to access some memory in a particular way that it shouldn’t. When you get one of these errors, you might be giving a program some input that it did not expect.

分段谬误基本上意味着刚刚运行的程序的编写者呈现了谬误。

该程序试图拜访不容许拜访的内存局部,导致操作系统将其终止。

相似地,总线谬误意味着程序试图以某种不应该的形式拜访某个内存。

当您遇到这些谬误时,可能是给程序输出了它不冀望的内容。

2.16 Listing and Manipulating Processes(过程的列举和操作)

Recall from Chapter 1 that a process is a running program. Each process on the system has a numeric process ID (PID). For a quick listing of running processes, just run ps on the command line. You should get a list like this one:

回顾一下第一章,过程是正在运行的程序。零碎上的每个过程都有一个数字过程 ID(PID)。要疾速列出正在运行的过程,只需在命令行上运行 ps 命令。您应该会失去一个相似上面的列表:

$ ps
 PID TTY STAT TIME COMMAND
 520 p0 S 0:00 -bash
 545 ? S 3:59 /usr/X11R6/bin/ctwm -W
 548 ? S 0:10 xclock -geometry -0-0
2159 pd SW 0:00 /usr/bin/vi lib/addresses
31956 p3 R 0:00 ps

The fields are as follows:

o PID. The process ID.
o TTY. The terminal device where the process is running. More about this later.
o STAT. The process status, that is, what the process is doing and where its memory resides. For example, S means sleeping and R means running. (See the ps(1) manual page for a description of all the symbols.)
o TIME. The amount of CPU time in minutes and seconds that the process has used so far. In other words, the total amount of time that the process has spent running instructions on the processor.
o COMMAND. This one might seem obvious, but be aware that a process can change this field from its original value.

字段的含意如下:
o PID:过程 ID。
o TTY:过程运行的终端设备。对于此前面会有更多介绍。
o STAT:过程的状态,即过程正在做什么以及其内存所在的地位。例如,S 示意睡眠,R 示意运行。(无关所有符号的形容,请参阅 ps(1)手册页。)
o TIME:过程到目前为止应用的 CPU 工夫(以分钟和秒为单位)。换句话说,过程在处理器上运行指令所破费的总工夫。
o COMMAND:这个可能看起来很显著,但请留神,过程能够将此字段从其原始值更改为其余值。

2.16.1 命令选项

The ps command has many options. To make things more confusing, you can specify options in three different styles—Unix, BSD, and GNU. Many people find the BSD style to be the most comfortable (perhaps because it involves less typing), so we’ll use the BSD style in this book. Here are some of the most useful option combinations:

ps 命令有许多选项。为了使事件更加凌乱,你能够以三种不同的格调指定选项——Unix、BSD 和 GNU。

许多人发现 BSD 格调最舒服(兴许是因为它须要更少的打字),所以在本书中咱们将应用 BSD 格调。以下是一些最有用的选项组合:

As with other programs, you can combine options, as in ps aux and ps auxw. To check on a specific
process, add its PID to the argument list of the ps command. For example, to inspect the current shell process,
you could use ps &dollar;&dollar;, because &dollar;&dollar; is a shell variable that evaluates to the current shell’s PID. (You’ll find
information on the administration commands top and lsof in Chapter 8. These can be useful for locating
processes, even when doing something other than system maintenance.)

与其余程序一样,您能够组合选项,例如 ps aux 和 ps auxw。

要查看特定过程,请将其 PID 增加到 ps 命令的参数列表中。

例如,要查看以后 shell 过程,能够应用 ps u &dollar;&dollar;,因为 &dollar;&dollar; 是一个 shell 变量,它的值为以后 shell 的 PID。

(对于治理命令 top 和 lsof 的信息能够在第 8 章找到。即便在进行系统维护以外的操作时,它们也能够用于定位过程。)

2.16.2 Killing Processes(终止过程)

To terminate a process, send it a signal with the kill command. A signal is a message to a process from the kernel. When you run kill, you’re asking the kernel to send a signal to another process. In most cases, all you need to do is this:

要终止一个过程,请应用 kill 命令向其发送一个信号。信号是内核向过程发送的一条音讯。

当您运行 kill 命令时,您正在申请内核向另一个过程发送一个信号。

在大多数状况下,您只须要执行以下操作:

$ kill pid

There are many types of signals. The default is TERM, or terminate. You can send different signals by adding an extra option to kill. For example, to freeze a process instead of terminating it, use the STOP signal:

有许多类型的信号。默认信号是 TERM,即终止。您能够通过在 kill 命令中增加额定选项来发送不同的信号。例如,要解冻一个过程而不是终止它,请应用 STOP 信号:

$ kill -STOP pid

A stopped process is still in memory, ready to pick up where it left off. Use the CONT signal to continue running the process again:

一个被进行的过程依然在内存中,筹备持续从上次进行的中央继续执行。应用 CONT 信号能够持续运行该过程:

$ kill -CONT pid

NOTE

Using ctrl-c to terminate a process that is running in the current terminal is the same as using kill to end the process with the INT (interrupt) signal.

留神

在以后终端中应用 ctrl- c 终止正在运行的过程与应用 kill 命令以 INT(中断)信号完结过程是雷同的。

The most brutal way to terminate a process is with the KILL signal. Other signals give the process a chance to clean up after itself, but KILL does not. The operating system terminates the process and forcibly removes it from memory. Use this as a last resort.

终止过程最仁慈的形式是应用 KILL 信号。其余信号给予过程一个机会自我清理,但 KILL 不会。

操作系统终止过程并强制从内存中移除它。

请将其视为最初的伎俩。

You should not kill processes indiscriminately, especially if you don’t know what they’re doing. You may be shooting yourself in the foot.

您不应该随便终止过程,特地是当您不晓得它们在做什么时。您可能会自作自受。

You may see other users entering numbers instead of names with kill; for example, kill -9 instead of kill -KILL. This is because the kernel uses numbers to denote the different signals; you can use kill this way if you know the number of the signal that you want to send.

您可能会看到其余用户应用数字而不是名称输出 kill 命令;例如,kill - 9 而不是 kill -KILL。

这是因为内核应用数字来示意不同的信号;如果您晓得要发送的信号的编号,能够应用这种形式。

2.16.3 Job Control(作业控制)

Shells also support job control, which is a way to send TSTP (similar to STOP) and CONT signals to programs by using various keystrokes and commands. For example, you can send a TSTP signal with CTRL-Z, then start the process again by entering fg (bring to foreground) or bg (move to background; see the next section). But despite its utility and the habits of many experienced users, job control is not necessary and can be confusing for beginners: It’s common for users to press CTRL-Z instead of CTRL-c, forget about what they were running, and eventually end up with numerous suspended processes hanging around.

Shell 还反对作业控制,这是一种通过应用各种按键和命令向程序发送 TSTP(相似于 STOP)和 CONT 信号的形式。

例如,你能够应用 CTRL-Z 发送 TSTP 信号,而后通过输出 fg(将过程带到前台)或 bg(移到后盾;请参见下一节)来重新启动过程。

然而,只管它很实用并且许多有教训的用户习惯应用它,但作业控制对于初学者来说并不是必须的,可能会造成困惑:用户常常按下 CTRL-Z 而不是 CTRL-C,遗记他们正在运行什么,最终导致大量挂起的过程存在。

HINT To see if you’ve accidentally suspended any processes on your current terminal, run the jobs command.

提醒

要查看是否在以后终端上意外挂起了任何过程,请运行 jobs 命令。

If you want to run multiple shells, run each program in a separate terminal window, put noninteractive processes in the background (as explained in the next section), or learn to use the screen program.

如果你想运行多个 shell,请在独自的终端窗口中运行每个程序,将非交互式过程放在后盾(如下一节所述),或学习应用 screen 程序。

2.16.4 Background Processes(后盾过程)

Normally, when you run a Unix command from the shell, you don’t get the shell prompt back until the program finishes executing. However, you can detach a process from the shell and put it in the“background”with the ampersand (&); this gives you the prompt back. For example, if you have a large file that you need to decompress with gunzip (you’ll see this in 2.18 Archiving and Compressing Files), and you want to do some other stuff while it’s running, run a command like this one:

通常,当你从 shell 运行 Unix 命令时,直到程序执行实现,你才会失去 shell 提示符。

然而,你能够应用和号(&)将一个过程从 shell 中拆散并放到“后盾”;这样你就可能立刻失去提示符。

例如,如果你有一个须要应用 gunzip(你将在 2.18 文件归档和压缩 中看到)解压缩的大文件,并且你心愿在它运行时做其余事件,能够运行以下命令:

$ gunzip file.gz &

The shell should respond by printing the PID of the new background process, and the prompt should return immediately so that you can continue working. The process will continue to run after you log out, which comes in particularly handy if you have to run a program that does a lot of number crunching for a while. (Depending on your setup, the shell might notify you when the process completes.)

Shell 应该会打印新后盾过程的 PID,并立刻返回提示符,以便你能够持续工作。

该过程将在你退出登录后持续运行,这在你须要运行一个进行大量数值计算的程序时特地不便。

(依据你的设置,当过程实现时,shell 可能会告诉你。)

The dark side of running background processes is that they may expect to work with the standard input (or worse, read directly from the terminal). If a program tries to read something from the standard input when it’s in the background, it can freeze (try fg to bring it back) or terminate. Also, if the program writes to the standard output or standard error, the output can appear in the terminal window with no regard for anything else running there, meaning that you can get unexpected output when you’re working on something else.

运行后盾过程的不好之处在于它们可能心愿与规范输出一起工作(或更蹩脚的是,间接从终端读取)。

如果一个程序在后盾时尝试从规范输出读取内容,它可能会解冻(尝试应用 fg 将其带回前台)或终止。

此外,如果程序写入规范输入或规范谬误,输入可能会呈现在终端窗口中,而不思考其余正在运行的内容,这意味着在你解决其余事件时可能会失去意外的输入。

The best way to make sure that a background process doesn’t bother you is to redirect its output (and possibly input) as described in 2.14 Shell Input and Output.

确保后盾过程不会打搅你的最佳办法是依据 2.14 Shell 输出和输入 中所述重定向其输入(和可能的输出)。

If spurious output from background processes gets in your way, learn how to redraw the content of your terminal window. The bash shell and most full-screen interactive programs support CTRL-L to redraw the entire screen. If a program is reading from the standard input, CTRL-R usually redraws the current line, but pressing the wrong sequence at the wrong time can leave you in an even worse situation than before. For example, entering CTRL-R at the bash prompt puts you in reverse isearch mode (press ESC to exit).

如果后盾过程产生了无关紧要的输入,学习如何从新绘制终端窗口的内容。

bash shell 和大多数全屏交互式程序都反对应用 CTRL- L 从新绘制整个屏幕。

如果一个程序正在读取规范输出,通常应用 CTRL- R 从新绘制以后行,然而在谬误的工夫按下谬误的序列可能会使状况变得更糟。

例如,在 bash 提示符下输出 CTRL- R 会进入反向搜寻模式(按 ESC 键退出)。

2.17 File Modes and Permissions(文件模式和权限)

Every Unix file has a set of permissions that determine whether you can read, write, or run the file. Running ls -l displays the permissions. Here’s an example of such a display:

每个 Unix 文件都有一组权限,确定您是否能够读取、写入或运行该文件。

运行 ls - l 命令显示权限。以下是一个示例显示:

-rw-r--r--➊ 1 juser somegroup 7041 Mar 26 19:34 endnotes.html

The file’s mode ➊ represents the file’s permissions and some extra information. There are four parts to the mode, as illustrated in Figure 2-1.

文件的模式 ➊ 示意文件的权限和一些额定信息。模式有四个局部,如图 2 - 1 所示。

The first character of the mode is the file type. A dash (-) in this position, as in the example, denotes a regular file, meaning that there’s nothing special about the file. This is by far the most common kind of file. Directories are also common and are indicated by a d in the file type slot. (3.1 Device Files lists the remaining file types.)

模式的第一个字符是文件类型。

在这个地位上的短横线(-),如示例中所示,示意一般文件,意味着该文件没有任何非凡之处。

这是最常见的文件类型。目录也很常见,通过文件类型地位上的 d 来示意。

(3.1 设施文件列出了其余文件类型。)

The rest of a file’s mode contains the permissions, which break down into three sets: user, group, and other, in that order. For example, the rw- characters in the example are the user permissions, the r– characters that follow are the group permissions, and the final r– characters are the other permissions.

文件的其余部分蕴含权限信息,这些权限能够分为三个汇合:用户、组和其余,依照这个程序。

例如,在示例中,rw- 字符是用户权限,前面的 r – 字符是组权限,最初的 r – 字符是其余权限。

每个权限汇合能够蕴含四种根本示意形式。

Each permission set can contain four basic representations:

The user permissions (the first set) pertain to the user who owns the file. In the preceding example, that’s juser. The second set, group permissions, are for the file’s group (somegroup in the example). Any user in that group can take advantage of these permissions. (Use the groups command to see what group you’re in, and see 7.3.5 Working with Groups for more information.)

用户权限(第一组)实用于领有该文件的用户。

在下面的例子中,这个用户是 juser。

第二组,组权限,实用于文件所属的组(在例子中是 somegroup)。

该组中的任何用户都能够利用这些权限。

(应用 groups 命令查看您所在的组,并参阅 7.3.5“与组一起应用”理解更多信息。)

Everyone else on the system has access according to the third set, the other permissions, which are sometimes called world permissions.

零碎中的其余所有用户依据第三组权限,也就是其余权限,来进行拜访,有时也称为全局权限。

NOTE Each read, write, and execute permission slot is sometimes called a permission bit. Therefore, you may hear people refer to parts of the permissions as“the read bits.”

留神:每个读取、写入和执行权限位有时被称为权限位。

因而,您可能会听到人们将权限的局部称为“读取位”。

Some executable files have an s in the user permissions listing instead of an x. This indicates that the executable is setuid, meaning that when you execute the program, it runs as though the file owner is the user instead of you. Many programs use this setuid bit to run as root in order to get the privileges they need to change system files. One example is the passwd program, which needs to change the /etc/passwd file.

某些可执行文件在用户权限列表中应用 s 而不是 x。

这示意可执行文件是设置了 setuid 位,意味着当您执行该程序时,它将以文件所有者而不是您的身份运行。

许多程序应用这个 setuid 位以 root 身份运行,以获取它们须要更改系统文件的特权。

一个例子是 passwd 程序,它须要更改 /etc/passwd 文件。

2.17.1 Modifying Permissions 批改权限

To change permissions, use the chmod command. First, pick the set of permissions that you want to change, and then pick the bit to change. For example, to add group (g) and world (o, for“other”) read (r) permissions to file, you could run these two commands:

要批改权限,应用 chmod 命令。首先,抉择要更改的权限集,而后抉择要更改的位。

例如,要将组(g)和其余(o,示意“其他人”)的读取(r)权限增加到文件中,能够运行以下两个命令:

$ chmod g+r file
$ chmod o+r file

Or you could do it all in one shot:

或者您也能够一次实现所有操作:

$ chmod go+r file

To remove these permissions, use go-r instead of go+r.

要删除这些权限,应用 go- r 而不是 go+r。

NOTE

Obviously, you shouldn’t make files world-writable because doing so gives anyone on your system the ability to change them. But would this allow anyone connected to the Internet to change your files? Probably not, unless your system has a network security hole. In that case, file permissions won’t help you anyway.

留神

显然,您不应该将文件设置为全局可写,因为这样做会使零碎上的任何人都可能更改它们。然而,这样做是否容许连贯到互联网的任何人更改您的文件呢?可能不会,除非您的零碎存在网络安全破绽。在这种状况下,文件权限也无奈帮忙您。

You may sometimes see people changing permissions with numbers, for example:

有时您会看到人们应用数字来更改权限,例如:

$ chmod 644 file

This is called an absolute change because it sets all permission bits at once. To understand how this works, you need to know how to represent the permission bits in octal form (each numeral represents a number in base 8 and corresponds to a permission set). See the chmod(1) manual page or info manual for more.

这被称为相对更改,因为它一次设置了所有权限位。

要了解其工作原理,您须要晓得如何以八进制模式示意权限位(每个数字代表 8 进制中的一个数字,并对应一个权限集)。

无关更多信息,请参阅 chmod(1)手册页或 info 手册。

You don’t really need to know how to construct absolute modes; just memorize the modes that you use most often. Table 2-4 lists the most common ones.

您实际上不须要晓得如何结构相对模式;只需记住您常常应用的模式即可。表 2 - 4 列出了最常见的模式。

Table 2-4. Absolute Permission Modes

Directories also have permissions. You can list the contents of a directory if it’s readable, but you can only access a file in a directory if the directory is executable. (One common mistake people make when setting the permissions of directories is to accidentally remove the execute permission when using absolute modes.)

目录也有权限。

如果目录可读,你能够列出目录的内容;但只有当目录可执行时,你能力拜访目录中的文件。

(设置目录权限时,人们常犯的一个谬误是在应用相对模式时意外删除了执行权限。)

Finally, you can specify a set of default permissions with the umask shell command, which applies a predefined set of permissions to any new file you create. In general, use umask 022 if you want everyone to be able to see all of the files and directories that you create, and use umask 077 if you don’t. (You’ll need to put the umask command with the desired mode in one of your startup files to make your new default permissions apply to later sessions, as discussed in Chapter 13.)

最初,你能够应用 umask shell 命令指定一组默认权限,该命令会将预约义的权限利用于你创立的任何新文件。

一般来说,如果你心愿每个人都能看到你创立的所有文件和目录,请应用 umask 022;如果不心愿每个人都能看到,请应用 umask 077。

(你须要将 umask 命令与所需模式放在其中一个启动文件中,以使新的默认权限实用于后续会话,如第 13 章所探讨的。)

2.17.2 Symbolic Links(符号链接)

A symbolic link is a file that points to another file or a directory, effectively creating an alias (like a shortcut in Windows). Symbolic links offer quick access to obscure directory paths.

符号链接是一个指向另一个文件或目录的文件,实际上创立了一个别名(相似于 Windows 中的快捷方式)。

符号链接能够快速访问艰涩的目录门路。

In a long directory listing, symbolic links look like this (notice the l as the file type in the file mode):

在长目录列表中,符号链接看起来像这样(留神文件模式中的 l 作为文件类型):

lrwxrwxrwx 1 ruser users 11 Feb 27 13:52 somedir -> /home/origdir

If you try to access somedir in this directory, the system gives you /home/origdir instead. Symbolic links are simply names that point to other names. Their names and the paths to which they point don’t have to mean anything. For example, /home/origdir doesn’t even need to exist.

如果您尝试在此目录中拜访 somedir,零碎会给您提供 /home/origdir。

符号链接只是指向其余名称的名称。它们的名称和指向的门路不用有任何意义。

例如,/home/origdir 甚至不须要存在。

In fact, if /home/origdir does not exist, any program that accesses somedir reports that somedir doesn’t exist (except for ls somedir, a command that stupidly informs you that somedir is somedir). This can be baffling because you can see something named somedir right in front of your eyes.

实际上,如果 /home/origdir 不存在,拜访 somedir 的任何程序都会报告 somedir 不存在(除了 ls somedir,这个命令愚蠢地告诉您 somedir 是 somedir)。

这可能会令人困惑,因为你能够看到眼前就有一个名为 somedir 的货色。

This is not the only way that symbolic links can be confusing. Another problem is that you can’t identify the characteristics of a link target just by looking at the name of the link; you must follow the link to see if it goes to a file or directory. Your system may also have links that point to other links, which are called chained symbolic links.

这不是符号链接可能令人困惑的惟一形式。

另一个问题是,仅仅通过查看链接的名称,您无奈确定链接指标的个性;您必须追随链接以查看它指向的是文件还是目录。

您的零碎还可能存在指向其余链接的链接,这被称为链接链。

2.17.3 Creating Symbolic Links(创立符号链接)

To create a symbolic link from target to linkname, use ln -s:

要从指标到链接名创立符号链接,请应用 ln - s 命令:

$ ln -s target linkname

The linkname argument is the name of the symbolic link, the target argument is the path of the file or directory that the link points to, and the -s flag specifies a symbolic link (see the warning that follows).

链接名参数是符号链接的名称,指标参数是链接指向的文件或目录的门路,- s 选项指定了一个符号链接(请参阅前面的正告)。

When making a symbolic link, check the command twice before you run it because several things can go wrong. For example, if you reverse the order of the arguments (ln -s linkname target), you’re in for some fun if linkname is a directory that already exists. If this is the case (and it quite often is), ln creates a link named target inside linkname, and the link will point to itself unless linkname is a full path. If something goes wrong when you create a symbolic link to a directory, check that directory for errant symbolic links and remove them.

在创立符号链接时,请在运行之前仔细检查命令,因为可能会呈现多种问题。

例如,如果您颠倒了参数的程序(ln -s 链接名 指标),如果链接名是一个曾经存在的目录,那么您就会遇到一些麻烦。

如果是这种状况(而且这种状况常常产生),ln 会在链接名外部创立一个名为指标的链接,并且该链接将指向本身,除非链接名是一个残缺门路。

如果在创立指向目录的符号链接时呈现问题,请查看该目录是否存在谬误的符号链接并将其删除。

Symbolic links can also cause headaches when you don’t know that they exist. For example, you can easily edit what you think is a copy of a file but is actually a symbolic link to the original.

当您不晓得符号链接存在时,它们也可能引起麻烦。

例如,您可能会轻易地编辑您认为是文件正本的货色,但实际上它是指向原始文件的符号链接。

WARNING
Don’t forget the -s option when creating a symbolic link. Without it, ln creates a hard link, giving an additional real filename to a single file. The new filename has the status of the old one; it points (links) directly to the file data instead of to another filename as a symbolic link does. Hard links can be even more confusing than symbolic links. Unless you understand the material in 4.5 Inside a Traditional Filesystem, avoid using them.

留神
在创立符号链接时,不要遗记应用“-s”选项。

如果没有应用该选项,ln 命令会创立一个硬链接,为单个文件提供一个额定的实在文件名。

新的文件名具备旧文件名的状态;它间接指向文件数据,而不像符号链接那样指向另一个文件名。

硬链接可能比符号链接更令人困惑。

除非你了解 4.5 节“传统文件系统外部”的内容,否则请防止应用硬链接。

With all of these warnings regarding symbolic links, why would anyone bother to use them? Because they offer a convenient way to organize and share files, as well as patch up small problems.

鉴于所有这些对于符号链接的正告,为什么还有人会费神去应用它们呢?

因为它们提供了一种不便的形式来组织和共享文件,以及修复小问题。

2.18 Archiving and Compressing Files(归档和压缩文件)

Now that you’ve learned about files, permissions, and possible errors, you need to master gzip and tar.

当初你曾经学会了对于文件、权限和可能的谬误,你须要把握 gzip 和 tar。

2.18.1 gzip

The program gzip (GNU Zip) is one of the current standard Unix compression programs. A file that ends with .gz is a GNU Zip archive. Use gunzip file.gz to uncompress .gz and remove the suffix; to compress it again, use gzip file.

gzip(GNU Zip)是以后规范的 Unix 压缩程序之一。

以.gz 结尾的文件是 GNU Zip 归档文件。应用 gunzip file.gz 来解压缩 < file>.gz 并移除后缀;要再次压缩它,应用 gzip file。

2.18.2 tar

Unlike the zip programs for other operating systems, gzip does not create archives of files; that is, it doesn’t pack multiple files and directories into one file. To create an archive, use tar instead:

与其余操作系统的 zip 程序不同,gzip 不会创立文件的归档;

也就是说,它不会将多个文件和目录打包成一个文件。要创立一个归档文件,应用 tar:

$ tar cvf archive.tar file1 file2 ...

Archives created by tar usually have a .tar suffix (this is by convention; it isn’t required). For example, in the command above, file1, file2, and so on are the names of the files and directories that you wish to archive in .tar. The c flag activates create mode. The r and f flags have more specific roles.

由 tar 创立的归档文件通常具备.tar 后缀(这是依照约定,不是必须的)。

例如,在上述命令中,file1、file2 等是您心愿在 < archive>.tar 中归档的文件和目录的名称。

c 标记激活创立模式。r 和 f 标记具备更具体的作用。

The v flag activates verbose diagnostic output, causing tar to print the names of the files and directories in the archive when it encounters them. Adding another v causes tar to print details such as file size and permissions. If you don’t want tar to tell you what it’s doing, omit the v flag.

v 标记激活具体诊断输入,当 tar 遇到文件和目录时,它会打印归档中的文件和目录的名称。

增加另一个 v 会导致 tar 打印诸如文件大小和权限之类的详细信息。如果您不想让 tar 告诉您它在做什么,省略 v 标记。

The f flag denotes the file option. The next argument on the command line after the f flag must be the archive file for tar to create (in the preceding example, it is .tar). You must use this option followed by a filename at all times, except with tape drives. To use standard input or output, enter a dash (-) instead of the filename.

f 标记示意文件选项。f 标记后的命令行参数必须是 tar 要创立的归档文件(在下面的例子中,它是 < archive>.tar)。

除了磁带驱动器外,您必须始终应用此选项后跟文件名。

要应用规范输出或输入,请在文件名处输出破折号(-)。

Unpacking tar files(解压 tar 文件)

To unpack a .tar file with tar use the x flag:

要应用 tar 解压缩.tar 文件,请应用 x 标记:

$ tar xvf archive.tar

In this command, the x flag puts tar into extract (unpack) mode. You can extract individual parts of the archive by entering the names of the parts at the end of the command line, but you must know their exact names. (To find out for sure, see the table-of-contents mode described shortly.)

在此命令中,x 标记将 tar 置于提取(解压缩)模式。

您能够通过在命令行的开端输出局部的名称来提取归档的各个局部,但必须晓得它们的确切名称。

(要确切理解,请参见前面形容的目录构造模式。)

NOTE When using extract mode, remember that tar does not remove the archived .tar file after extracting its contents.

留神

在应用提取模式时,请记住 tar 在提取内容后不会删除归档的.tar 文件。

Table-of-Contents Mode(目录构造模式)

Before unpacking, it’s usually a good idea to check the contents of a .tar file with the table-of-contents mode by using the t flag instead of the x flag. This mode verifies the archive’s basic integrity and prints the names of all files inside. If you don’t test an archive before unpacking it, you can end up dumping a huge mess of files into the current directory, which can be really difficult to clean up.

在解压缩之前,通常最好应用 t 标记而不是 x 标记来查看.tar 文件的内容。

此模式验证归档的根本完整性并打印所有文件的名称。

如果在解压缩之前不测试归档文件,可能会导致将大量文件倾倒到当前目录中,这可能十分难以清理。

When you check an archive with the t mode, verify that everything is in a rational directory structure; that is, all file pathnames in the archive should start with the same directory. If you’re unsure, create a temporary directory, change to it, and then extract. (You can always use mv * .. if the archive didn’t create a mess.)

在应用 t 模式查看归档文件时,请验证所有文件路径名是否以雷同目录结尾,即归档中的所有文件路径名都应该以雷同的目录结尾。

如果不确定,请创立一个长期目录,切换到该目录,而后进行提取。

(如果归档没有创立凌乱,您始终能够应用 mv * .. 命令。)

When unpacking, consider using the p option to preserve permissions. Use this in extract mode to override your umask and get the exact permissions specified in the archive. The p option is the default when working as the superuser. If you’re having trouble with permissions and ownership when unpacking an archive as the superuser, make sure that you are waiting until the command terminates and you get the shell prompt back. Although you may only want to extract a small part of an archive, tar must run through the whole thing, and you must not interrupt the process because it sets the permissions only after checking the entire archive

在解压缩时,思考应用 p 选项来保留权限。

在提取模式下应用此选项能够笼罩您的 umask 并取得归档中指定的确切权限。

当以超级用户身份工作时,p 选项是默认选项。

如果在以超级用户身份解压缩归档时遇到权限和所有权问题,请确保期待命令终止并取得 shell 提示符。

只管您可能只想提取归档的一小部分,但 tar 必须运行整个过程,您不能中断该过程,因为它仅在查看残缺个归档后才设置权限。

Commit all of the tar options and modes in this section to memory. If you’re having trouble, make some flash cards. This may sound like grade-school, but it’s very important to avoid careless mistakes with this command.

请牢记本节中的所有 tar 选项和模式。

如果遇到问题,请制作一些记忆卡。

这听起来可能像小学生,但防止在此命令中呈现大意谬误十分重要。

2.18.3 Compressed Archives (.tar.gz)(压缩归档文件 (.tar.gz))

Many beginners find it confusing that archives are normally found compressed, with filenames ending in .tar.gz. To unpack a compressed archive, work from the right side to the left; get rid of the .gz first and then worry about the .tar. For example, these two commands decompress and unpack .tar.gz:

许多初学者对于归档文件通常是以压缩模式呈现,并以.tar.gz 作为文件扩展名感到困惑。

要解压缩压缩的归档文件,从右到左进行操作;首先去掉.gz,而后再解决.tar。

例如,以下两个命令能够解压缩并解包 < file>.tar.gz:

$ gunzip file.tar.gz
$ tar xvf file.tar

When starting out, you can do this one step at a time, first running gunzip to decompress and then tar to verify and unpack. To create a compressed archive, do the reverse; run tar first and gzip second. Do this frequently enough, and you’ll soon memorize how the archiving and compression process works. You’ll also get tired of all of the typing and start to look for shortcuts. Let’s take a look at those now.

刚开始时,你能够一步一步地进行操作,先运行 gunzip 进行解压缩,而后再运行 tar 进行验证和解包。

要创立一个压缩的归档文件,反过来操作;先运行 tar,而后再运行 gzip。

常常这样操作,你很快就会记住归档和压缩的过程是如何工作的。

你也会厌倦输出这么多命令,开始寻找快捷方式。

当初让咱们来看看这些快捷方式。

2.18.4 zcat

The method shown above isn’t the fastest or most efficient way to invoke tar on a compressed archive, and it wastes disk space and kernel I/O time. A better way is to combine archival and compression functions with a pipeline. For example, this command pipeline unpacks .tar.gz:

上述办法不是调用压缩归档文件最快、最高效的形式,而且会节约磁盘空间和内核 I / O 工夫。

更好的形式是将归档和压缩性能联合起来应用管道。

例如,以下命令通过管道解包 < file>.tar.gz:

$ zcat file.tar.gz | tar xvf -

The zcat command is the same as gunzip -dc. The -d option decompresses and the -c option sends the result to standard output (in this case, to the tar command).

zcat 命令与 gunzip -dc 命令雷同。

- d 选项用于解压缩,- c 选项将后果发送到规范输入(在这种状况下是 tar 命令)。

Because it’s so common to use zcat, the version of tar that comes with Linux has a shortcut. You can use z as an option to automatically invoke gzip on the archive; this works both for extracting an archive (with the x or t modes in tar) and creating one (with c). For example, use the following to verify a compressed archive:

因为应用 zcat 十分常见,Linux 自带的 tar 版本提供了一个快捷方式。

你能够应用 z 作为选项来主动调用 gzip 对归档文件进行解决;

对于解压缩归档文件(应用 tar 的 x 或 t 模式)和创立归档文件(应用 c 模式),这都实用。

例如,应用以下命令验证一个压缩的归档文件:

$ tar ztvf file.tar.gz

However, you should try to master the longer form before taking the shortcut

然而,在应用快捷方式之前,你应该尽量把握更长的模式。

NOTE A .tgz file is the same as a .tar.gz file. The suffix is meant to fit into FAT (MS-DOS-based) filesystems.

留神

tgz 文件与.tar.gz 文件雷同。后缀是为了适应 FAT(基于 MS-DOS 的)文件系统。

2.18.5 Other Compression Utilities(其余压缩工具)

Another compression program in Unix is bzip2, whose compressed files end with .bz2. While marginally slower than gzip, bzip2 often compacts text files a little more, and it is therefore increasingly popular in the distribution of source code. The decompressing program to use is bunzip2, and the options of both components are close enough to those of gzip that you don’t need to learn anything new. The bzip2 compression/decompression option for tar is j.

Unix 中的另一个压缩程序是 bzip2,其压缩文件的扩大名为.bz2。

尽管比 gzip 稍慢,但 bzip2 通常能够更好地压缩文本文件,因而在源代码的散发中越来越受欢迎。

用于解压缩的程序是 bunzip2,两个组件的选项与 gzip 的选项十分靠近,所以你不须要学习任何新常识。

tar 的 bzip2 压缩 / 解压缩选项是 j。

另一个名为 xz 的压缩程序也越来越受欢迎。相应的解压缩程序是 unxz,其参数与 gzip 的参数相似。

A new compression program named xz is also gaining popularity. The corresponding decompression program is unxz, and the arguments are similar to those of gzip. Most Linux distributions come with zip and unzip programs that are compatible with the zip archives on Windows systems. They work on the usual .zip files as well as self-extracting archives ending in .exe. But if you encounter a file that ends in .Z, you have found a relic created by the compress program, which was once the Unix standard. The gunzip program can unpack these files, but gzip won’t create them.

大多数 Linux 发行版都装备了与 Windows 零碎上的 zip 存档兼容的 zip 和 unzip 程序。

它们能够解决通常的.zip 文件,也能够解决以.exe 结尾的自解压存档。

然而,如果你遇到以.Z 结尾的文件,那么你找到的是由 compress 程序创立的遗留文件,这已经是 Unix 的规范。

gunzip 程序能够解压这些文件,但 gzip 不能创立它们。

2.19 Linux Directory Hierarchy Essentials(Linux 目录层次结构根底)

Now that you know how to examine files, change directories, and read manual pages, you’re ready to start exploring your system files. The details of the Linux directory structure are outlined in the Filesystem Hierarchy Standard, or FHS (http://www.pathname.com/fhs/), but a brief walkthrough should suffice for now

当初你曾经晓得如何查看文件、更改目录和浏览手册页,你能够开始摸索系统文件了。

Linux 目录构造的详细信息在文件系统层次结构规范(Filesystem Hierarchy Standard,简称 FHS)中有介绍(http://www.pathname.com/fhs/),然而简要的概述当初应该足够了。

Figure 2-2 offers a simplified overview of the hierarchy, showing some of the directories under /, /usr, and /var. Notice that the directory structure under /usr contains some of the same directory names as /.

图 2 - 2 提供了层次结构的简化概述,显示了 /、/usr 和 /var 下的一些目录。

请留神,/usr 下的目录构造蕴含了与 / 下雷同的目录名。

Figure 2-2. Linux directory hierarchy

Here are the most important subdirectories in root:

以下是根目录中最重要的子目录:

o /bin Contains ready-to-run programs (also known as an executables), including most of the basic Unix commands such as ls and cp. Most of the programs in /bin are in binary format, having been created by a C compiler, but some are shell scripts in modern systems.

o /dev Contains device files. You’ll learn more about these in Chapter 3.

o /etc This core system configuration directory (pronounced EHT-see) contains the user password, boot, device, networking, and other setup files. Many items in /etc are specific to the machine’s hardware. For example, the /etc/X11 directory contains graphics card and window system configurations.

o /home Holds personal directories for regular users. Most Unix installations conform to this standard.

o /lib An abbreviation for library, this directory holds library files containing code that executables can use. There are two types of libraries: static and shared. The /lib directory should contain only shared libraries, but other lib directories, such as /usr/lib, contain both varieties as well as other auxiliary files. (We’ll discuss shared libraries in more detail in Chapter 15.)

o /proc Provides system statistics through a browsable directory-and-file interface. Much of the /proc subdirectory structure on Linux is unique, but many other Unix variants have similar features. The /proc directory contains information about currently running processes as well as some kernel parameters.

o /sys This directory is similar to /proc in that it provides a device and system interface. You’ll read more about /sys in Chapter 3.

o /sbin The place for system executables. Programs in /sbin directories relate to system management, so regular users usually do not have /sbin components in their command paths. Many of the utilities found here will not work if you’re not running them as root.

o /tmp A storage area for smaller, temporary files that you don’t care much about. Any user may read to and write from /tmp, but the user may not have permission to access another user’s files there. Many programs use this directory as a workspace. If something is extremely important, don’t put it in /tmp because most distributions clear /tmp when the machine boots and some even remove its old files periodically. Also, don’t let /tmp fill up with garbage because its space is usually shared with something critical (like the rest of /, for example).

o /usr Although pronounced“user,”this subdirectory has no user files. Instead, it contains a large directory hierarchy, including the bulk of the Linux system. Many of the directory names in /usr are the same as those in the root directory (like /usr/bin and /usr/lib), and they hold the same type of files. (The reason that the root directory does not contain the complete system is primarily historic—in the past, it was to keep space requirements low for the root.)

o /var The variable subdirectory, where programs record runtime information. System logging, user tracking, caches, and other files that system programs create and manage are here. (You’ll notice a /var/tmp directory here, but the system doesn’t wipe it on boot.

o /bin:蕴含可间接运行的程序(也称为可执行文件),包含大多数根本的 Unix 命令,如 ls 和 cp。/bin 目录中的大多数程序都是以二进制格局创立的,由 C 编译器生成,但在古代零碎中也有一些 shell 脚本。

o /dev:蕴含设施文件。您将在第 3 章中理解更多相干信息。

o /etc:这是外围系统配置目录(发音为 EHT-see),蕴含用户明码、疏导、设施、网络和其余设置文件。/etc 目录中的许多我的项目都是特定于机器硬件的。例如,/etc/X11 目录蕴含图形卡和窗口零碎的配置。

o /home:为普通用户提供集体目录。大多数 Unix 装置都合乎这个规范。

o /lib:缩写为库,该目录蕴含蕴含可执行文件能够应用的代码的库文件。有两种类型的库:动态库和共享库。/lib 目录只应蕴含共享库,但其余 lib 目录(例如 /usr/lib)也蕴含两种类型的库以及其余辅助文件。(咱们将在第 15 章中更具体地探讨共享库。)
o /proc:通过可浏览的目录和文件接口提供零碎统计信息。Linux 上的 /proc 子目录构造很独特,但许多其余 Unix 变种也具备相似的性能。/proc 目录蕴含无关以后运行的过程以及一些内核参数的信息。

o /sys:此目录相似于 /proc 目录,提供设施和零碎接口。您将在第 3 章中理解更多对于 /sys 目录的信息。

o /sbin:零碎可执行文件的地位。/sbin 目录中的程序与系统管理相干,因而普通用户通常不会在其命令门路中蕴含 /sbin 组件。这里找到的许多实用程序如果不以 root 身份运行,则无奈工作。

o /tmp 是一个存储较小、临时文件的区域,你对它并不太在意。任何用户都能够读取和写入 /tmp,但用户可能没有权限拜访其余用户在此处的文件。许多程序将此目录用作工作空间。如果某个文件十分重要,不要放在 /tmp 中,因为大多数发行版在机器启动时会革除 /tmp,有些甚至会定期删除其旧文件。此外,不要让 /tmp 充斥垃圾,因为它的空间通常与某些要害内容(例如根目录的其余局部)共享。

o /usr 尽管发音为“user”,但这个子目录没有用户文件。相同,它蕴含一个大型的目录层次结构,包含大部分 Linux 零碎。/usr 中的许多目录名与根目录中的目录名雷同(如 /usr/bin 和 /usr/lib),并且它们保留着雷同类型的文件。(根目录不蕴含残缺的零碎的起因次要是历史起因——过来为了使根目录的空间要求较低。)

o /var 是变量子目录,程序在此记录运行时信息。系统日志、用户跟踪、缓存和其余零碎程序创立和治理的文件都在这里。(你会留神到这里有一个 /var/tmp 目录,但零碎不会在启动时革除它。)

2.19.1 Other Root Subdirectories(其余根目录的子目录)

There are a few other interesting subdirectories in the root directory:

根目录中还有一些其余乏味的子目录:

o /boot Contains kernel boot loader files. These files pertain only to the very first stage of the Linux startup procedure; you won’t find information about how Linux starts up its services in this directory. See Chapter 5 for more about this.
o /media A base attachment point for removable media such as flash drives that is found in many distributions.
o /opt This may contain additional third-party software. Many systems don’t use /opt.

/boot 蕴含内核疏导加载程序文件。

这些文件只与 Linux 启动过程的最后阶段无关;你在这个目录中找不到对于 Linux 如何启动服务的信息。

无关此内容的更多信息,请参见第 5 章。

/media 是可挪动介质的根本附加点,如闪存驱动器,它在许多发行版中都存在。

/opt 可能蕴含额定的第三方软件。许多零碎不应用 /opt。

2.19.2 The /usr Directory(/usr 目录)

The /usr directory may look relatively clean at first glance, but a quick look at /usr/bin and /usr/lib reveals that there’s a lot here; /usr is where most of the user-space programs and data reside. In addition to /usr/bin, /usr/sbin, and /usr/lib, /usr contains the following:

/ usr 目录乍一看可能绝对洁净,但疾速查看 /usr/bin 和 /usr/lib 会发现这里有很多内容;

/usr 是大多数用户空间程序和数据所在的中央。

除了 /usr/bin、/usr/sbin 和 /usr/lib 之外,/usr 还蕴含以下内容:

o /include Holds header files used by the C compiler.
o /info Contains GNU info manuals (see 2.13 Getting Online Help).
o /local Is where administrators can install their own software. Its structure should look like that of / and /usr.
o /man Contains manual pages.
o /share Contains files that should work on other kinds of Unix machines with no loss of functionality. In the past, networks of machines would share this directory, but a true /share directory is becoming rare because there are no space issues on modern disks. Maintaining a /share directory is often just a pain. In any case, /man, /info, and some other subdirectories are often found here.

  • /include 保留 C 编译器应用的头文件。
  • /info 蕴含 GNU info 手册(见 2.13 获取在线帮忙)。
  • /local 是管理员能够装置本人软件的中央。它的构造应该相似于 / 和 /usr。
  • /man 蕴含手册页。
  • /share 蕴含应该在其余类型的 Unix 机器上失常工作的文件,而不会丢失性能。过来,机器网络会共享此目录,但真正的 /share 目录变得越来越少,因为古代磁盘没有空间问题。保护 /share 目录通常只是一种麻烦。无论如何,/man、/info 和其余一些子目录通常在这里找到。

2.19.3 Kernel Location(内核地位)

On Linux systems, the kernel is normally in /vmlinuz or /boot/vmlinuz. A boot loader loads this file into memory and sets it in motion when the system boots. (You’ll find details on the boot loader in Chapter 5.)

在 Linux 零碎中,内核通常位于 /vmlinuz 或 /boot/vmlinuz。

疏导加载程序会将此文件加载到内存中,并在系统启动时启动它。(无关疏导加载程序的详细信息,请参见第 5 章。)

Once the boot loader runs and sets the kernel in motion, the main kernel file is no longer used by the running system. However, you’ll find many modules that the kernel can load and unload on demand during the course of normal system operation. Called loadable kernel modules, they are located under /lib/modules.

一旦疏导加载程序运行并启动内核,运行中的零碎就不再应用主内核文件。

然而,在失常零碎操作过程中,您会发现许多内核能够依据须要加载和卸载的模块。

这些称为可加载内核模块,它们位于 /lib/modules 下。

2.20 Running Commands as the Superuser(以超级用户身份运行命令)

Before going any further, you should learn how to run commands as the superuser. You probably already know that you can run the su command and enter the root password to start a root shell. This practice works, but it has certain disadvantages:

在进一步操作之前,您应该学会如何以超级用户身份运行命令。

您可能曾经晓得能够运行 su 命令并输出 root 明码来启动 root shell。这种做法是可行的,但也存在一些毛病:

o You have no record of system-altering commands.
o You have no record of the users who performed system-altering commands.
o You don’t have access to your normal shell environment.
o You have to enter the root password.

  • 您无奈记录批改零碎的命令。
  • 您无奈记录执行批改系统命令的用户。
  • 您无法访问失常的 shell 环境。
  • 您须要输出 root 明码。

2.20.1 sudo

Most larger distributions use a package called sudo to allow administrators to run commands as root when they are logged in as themselves. For example, in Chapter 7, you’ll learn about using vipw to edit the /etc/passwd file. You could do it like this:

大多数较大的发行版应用一个名为 sudo 的软件包,容许管理员在以本人的身份登录时以 root 身份运行命令。例如,在第 7 章中,您将学习应用 vipw 编辑 /etc/passwd 文件。您能够像这样执行:

$ sudo vipw

When you run this command, sudo logs this action with the syslog service under the local2 facility. You’ll also learn more about system logs in Chapter 7.

运行此命令时,sudo 会将此操作记录在 syslog 服务的 local2 设施下。

在第 7 章中,您还将学习更多对于系统日志的内容。

2.20.2 /etc/sudoers

Of course, the system doesn’t let just any user run commands as the superuser; you must configure the privileged users in your /etc/sudoers file. The sudo package has many options (that you’ll probably never use), which makes the syntax in /etc/sudoers somewhat complicated. For example, this file gives user1 and user2 the power to run any command as root without having to enter a password:

当然,零碎不容许任何用户都以超级用户身份运行命令;您必须在 /etc/sudoers 文件中配置特权用户。

sudo 软件包有许多选项(您可能永远不会应用),这使得 /etc/sudoers 的语法有些简单。

例如,此文件容许 user1 和 user2 以 root 身份运行任何命令而无需输出明码:

User_Alias ADMINS = user1, user2
ADMINS ALL = NOPASSWD: ALL
root ALL=(ALL) ALL

The first line defines an ADMINS user alias with the two users, and the second line grants the privileges. The ALL = NOPASSWD: ALL part means that the users in the ADMINS alias can use sudo to execute commands as root. The second ALL means“any command.”The first ALL means“any host.”(If you have more than one machine, you can set different kinds of access for each machine or group of machines, but we won’t cover that feature.)

第一行定义了一个名为 ADMINS 的用户别名,其中蕴含两个用户,第二行授予了特权。

ALL = NOPASSWD: ALL 局部示意 ADMINS 别名中的用户能够应用 sudo 以 root 身份执行命令。

第二个 ALL 示意“任何命令”。

第一个 ALL 示意“任何主机”。(如果您有多台机器,能够为每台机器或一组机器设置不同的拜访权限,但咱们不会波及该性能。)

The root ALL=(ALL) ALL simply means that the superuser may also use sudo to run any command on any host. The extra (ALL) means that the superuser may also run commands as any other user. You can extend this privilege to the ADMINS users by adding (ALL) to the /etc/sudoers line, as shown at ➊: ADMINS ALL = (ALL)➊ NOPASSWD: ALL

root ALL=(ALL) ALL 简略地示意超级用户也能够应用 sudo 在任何主机上运行任何命令。

额定的 (ALL) 示意超级用户也能够以任何其余用户的身份运行命令。

您能够通过在 /etc/sudoers 行中增加 (ALL) 来将此特权扩大给 ADMINS 用户,如➊所示:
ADMINS ALL = (ALL)➊ NOPASSWD: ALL

NOTE Use the visudo command to edit /etc/sudoers. This command checks for file syntax errors after you save the file. That’s it for sudo for now. If you need to use its more advanced features, see the sudoers(5) and sudo(8) manual pages. (The actual mechanics of user switching are covered in Chapter 7.)

留神

应用 visudo 命令编辑 /etc/sudoers 文件。此命令在保留文件后会查看文件语法错误。

目前对于 sudo 的介绍就到这里了。

如果你须要应用它的更高级性能,请参阅 sudoers(5)和 sudo(8)的手册页面。

(无关用户切换的理论机制将在第 7 章中介绍。)

2.21 Looking Forward(展望未来)

You should now know how to do the following at the command line: run programs, redirect output, interact with files and directories, view process listings, view manual pages, and generally make your way around the user space of a Linux system. You should also be able to run commands as the superuser. You may not yet know much about the internal details of user-space components or what goes on in the kernel, but with the basics of files and processes under your belt, you’re on your way. In the next few chapters, you’ll be working with both kernel and user-space system components using the command-line tools that you just learned.

您当初应该晓得如何在命令行中执行以下操作:运行程序、重定向输入、与文件和目录交互、查看过程列表、查看手册页面,并且能够在 Linux 零碎的用户空间中自若地操作。

您还应该可能以超级用户身份运行命令。

兴许您对用户空间组件的外部细节或内核中产生的状况还不太理解,然而把握了文件和过程的基础知识后,您曾经迈出了第一步。

在接下来的几章中,您将应用刚刚学到的命令行工具来解决内核和用户空间零碎组件。


  1. . ↩

正文完
 0