【Linux】《how linux work》第二章 基本命令和目錄層次結構

發表於2024-03-01

第 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:

這本書包含了許多你將在命令列提示符下輸入的命令。

它們都以一個單獨的$符號開頭,用來表示命令列提示符。

例如,輸入這個命令(只輸入加粗部分,不包括$符號),然後按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

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

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. 聯機手冊章節

Table 2-3. Online Manual Sections

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風格。以下是一些最有用的選項組合:

image.png

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 裝置檔案列出了其他檔案型別。)

image.png

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:

image.png

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

image.png

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

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. .

相關文章