第 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)。
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 $$, because $$ 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 $$,因为 $$ 是一个 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系统的用户空间中自如地操作。
您还应该能够以超级用户身份运行命令。
也许您对用户空间组件的内部细节或内核中发生的情况还不太了解,但是掌握了文件和进程的基础知识后,您已经迈出了第一步。
在接下来的几章中,您将使用刚刚学到的命令行工具来处理内核和用户空间系统组件。
- . ↩
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。