TLCL

參考閱讀:http://billie66.github.io/TLCL/book/chap04.html

 

絕對路徑

An absolute pathname begins with the root directory and follows the tree branch by branch until the path to the desired directory or file is completed. For example, there is a directory on your system in which most of your system’s programs are installed. The pathname of the directory is /usr/bin. This means from the root directory (represented by the leading slash in the pathname) there is a directory called 「usr」 which contains a directory called 「bin」.html

絕對路徑開始於根目錄,緊跟着目錄樹的一個個分支,一直到達所指望的目錄或文件。 例如,你的系統中有一個目錄,大多數系統程序都安裝在這個目錄下。這個目錄的 路徑名是 /usr/bin。它意味着從根目錄(用開頭的「/」表示)開始,有一個叫 「usr」 的 目錄包含了目錄 「bin」。node

[me@linuxbox ~]$ cd /usr/bin
[me@linuxbox bin]$ pwd
/usr/bin
[me@linuxbox bin]$ ls
...Listing of many, many files ...

Now we can see that we have changed the current working directory to /usr/bin and that it is full of files. Notice how the shell prompt has changed? As a convenience, it is usually set up to automatically display the name of the working directory.python

咱們把工做目錄轉到 /usr/bin 目錄下,裏面裝滿了文件。注意 shell 提示符是怎樣改變的嗎? 爲了方便,一般終端提示符自動顯示工做目錄名。linux

相對路徑

Where an absolute pathname starts from the root directory and leads to its destination, a relative pathname starts from the working directory. To do this, it uses a couple of special symbols to represent relative positions in the file system tree. These special symbols are 「.」 (dot) and 「..」 (dot dot).git

絕對路徑從根目錄開始,直到它的目的地,而相對路徑開始於工做目錄。 爲了作到這個(用相對路徑表示), 咱們在文件系統樹中用一對特殊符號來表示相對位置。 這對特殊符號是 「.」 (點) 和 「..」 (點點)。github

The 「.」 symbol refers to the working directory and the 「..」 symbol refers to the working directory’s parent directory. Here is how it works. Let’s change the working directory to /usr/bin again:shell

符號 「.」 指的是工做目錄,」..」 指的是工做目錄的父目錄。下面的例子說明怎樣使用它。 讓咱們再次把工做目錄切換到 /usr/bin:數據庫

[me@linuxbox ~]$ cd /usr/bin
[me@linuxbox bin]$ pwd
/usr/bin

Okay, now let’s say that we wanted to change the working directory to the parent of /usr/bin which is /usr. We could do that two different ways. Either with an absolute pathname:express

好了,比方說咱們想更改工做目錄到 /usr/bin 的父目錄 /usr。能夠經過兩種方法來實現。可使用如下絕對路徑名:編程

[me@linuxbox bin]$ cd /usr
[me@linuxbox usr]$ pwd
/usr

Or, with a relative pathname:

或者, 也可使用相對路徑:

[me@linuxbox bin]$ cd ..
[me@linuxbox usr]$ pwd
/usr

Two different methods with identical results. Which one should we use? The one that requires the least typing!

兩種不一樣的方法,同樣的結果。咱們應該選哪個呢? 選輸入量最少的那個!

Likewise, we can change the working directory from /usr to /usr/bin in two different ways. Either using an absolute pathname:

一樣地,從目錄 /usr/ 到 /usr/bin 也有兩種途徑。可使用絕對路徑:

[me@linuxbox usr]$ cd /usr/bin
[me@linuxbox bin]$ pwd
/usr/bin

Or, with a relative pathname:

或者,也能夠用相對路徑:

[me@linuxbox usr]$ cd ./bin
[me@linuxbox bin]$ pwd
/usr/bin

Now, there is something important that I must point out here. In almost all cases, you can omit the 「./」. It is implied. Typing:

有一件很重要的事,我必須指出來。在幾乎全部的狀況下,你能夠省略」./」。它是隱含的。輸入:

[me@linuxbox usr]$ cd bin

does the same thing. In general, if you do not specify a pathname to something, the working directory will be assumed.

實現相同的效果。若是不指定一個文件的路徑,那它被默認爲在當前工做目錄下。

有用的快捷鍵

In table 3-1 we see some useful ways the current working directory can be quickly changed.

在表3-1中,列舉出了一些快速改變當前工做目錄的有效方法。

Table 3-1: cd Shortcuts
Shortcut Result
cd Changes the working directory to your home directory.
cd - Changes the working directory to the previous working directory.
cd ~user_name Changes the working directory to the home directory of user_name. For example, cd ~bob will change the directory to the home directory of user 「bob.」
表3-1: cd 快捷鍵
快捷鍵 運行結果
cd 更改工做目錄到你的家目錄。
cd - 更改工做目錄到先前的工做目錄。
cd ~user_name 更改工做目錄到用戶家目錄。例如, cd ~bob 會更改工做目錄到用戶「bob」的家目錄。

 

ls 樂趣

選項和參數

This brings us to a very important point about how most commands work. Commands are often followed by one or more options that modify their behavior, and further, by one or more arguments, the items upon which the command acts. So most commands look kind of like this:

咱們將學習一個很是重要的知識點,即大多數命令是如何工做的。命令名常常會帶有一個或多個用來更正命令行爲的選項, 更進一步,選項後面會帶有一個或多個參數,這些參數是命令做用的對象。因此大多數命令看起來像這樣:

command -options arguments

Most commands use options consisting of a single character preceded by a dash, for example, 「-l」, but many commands, including those from the GNU Project, also support long options, consisting of a word preceded by two dashes. Also, many commands allow multiple short options to be strung together. In this example, the ls command is given two options, the 「l」 option to produce long format output, and the 「t」 option to sort the result by the file’s modification time.

大多數命令使用的選項,是由一箇中劃線加上一個字符組成,例如,「-l」,可是許多命令,包括來自於 GNU 項目的命令,也支持長選項,長選項由兩個中劃線加上一個字組成。固然, 許多命令也容許把多個短選項串在一塊兒使用。下面這個例子,ls 命令有兩個選項, 「l」 選項產生長格式輸出,「t」選項按文件修改時間的前後來排序。

[me@linuxbox ~]$ ls -lt

We’ll add the long option 「–reverse」 to reverse the order of the sort:

加上長選項 「–reverse」,則結果會以相反的順序輸出:

[me@linuxbox ~]$ ls -lt --reverse

The ls command has a large number of possible options. The most common are listed in the Table 4-1.

ls 命令有大量的選項。表4-1列出了最常使用的選項。

Table 4-1: Common ls Options
Option Long Option Description
-a --all List all files, even those with names that begin with a period, which are normally not listed(i.e.,hidden).
-d --directory Ordinaryly,if a directory is specified, ls will list the contents of the directory, not the directory itself. Use this option in conjunction with the -l option to see details about the directory rather than its contents.
-F --classify This option will append an indicator character to the end of each listed name. For example, a '/' if the name is a directory.
-h --human-readable In long format listings, display file sizes in human readable format rather than in bytes.
-l   Display results in long format.
-r --reverse Display the results in reverse order. Normally, ls display its results in ascending alphabetical order.
-S   Sort results by file size.
-t   Sort by modification time.
表 4-1: ls 命令選項
選項 長選項 描述
-a --all 列出全部文件,甚至包括文件名以圓點開頭的默認會被隱藏的隱藏文件。
-d --directory 一般,若是指定了目錄名,ls 命令會列出這個目錄中的內容,而不是目錄自己。 把這個選項與 -l 選項結合使用,能夠看到所指定目錄的詳細信息,而不是目錄中的內容。
-F --classify 這個選項會在每一個所列出的名字後面加上一個指示符。例如,若是名字是 目錄名,則會加上一個'/'字符。
-h --human-readable 當以長格式列出時,以人們可讀的格式,而不是以字節數來顯示文件的大小。
-l   以長格式顯示結果。
-r --reverse 以相反的順序來顯示結果。一般,ls 命令的輸出結果按照字母升序排列。
-S   命令輸出結果按照文件大小來排序。
-t   按照修改時間來排序。

 

肯定文件類型

As we explore the system it will be useful to know what files contain. To do this we will use the file command to determine a file’s type. As we discussed earlier, filenames in Linux are not required to reflect a file’s contents. While a filename like 「picture.jpg」 would normally be expected to contain a JPEG compressed image, it is not required to in Linux. We can invoke the file command this way:

隨着探究操做系統的進行,知道文件包含的內容是頗有用的。咱們將用 file 命令來肯定文件的類型。咱們以前討論過, 在 Linux 系統中,並不要求文件名來反映文件的內容。然而,一個相似 「picture.jpg」 的文件名,咱們會指望它包含 JPEG 壓縮圖像,但 Linux 卻不這樣要求它。能夠這樣調用 file 命令:

file filename

When invoked, the file command will print a brief description of the file’s contents. For example:

當調用 file 命令後,file 命令會打印出文件內容的簡單描述。例如:

[me@linuxbox ~]$ file picture.jpg
picture.jpg: JPEG image data, JFIF standard 1.01

There are many kinds of files. In fact, one of the common ideas in Unix-like operating systems such as Linux is that 「everything is a file.」 As we proceed with our lessons, we will see just how true that statement is.

有許多種類型的文件。事實上,在類 Unix 操做系統中好比說 Linux 中,有個廣泛的觀念就是「一切皆文件」。 隨着課程的進行,咱們將會明白這句話是多麼的正確。

While many of the files on your system are familiar, for example MP3 and JPEG, there are many kinds that are a little less obvious and a few that are quite strange.

雖然系統中許多文件格式是熟悉的,例如 MP3和 JPEG 文件,但也有一些文件格式不太常見,極少數文件至關陌生。

旅行指南

The file system layout on your Linux system is much like that found on other Unix-like systems. The design is actually specified in a published standard called the Linux Filesystem Hierarchy Standard. Not all Linux distributions conform to the standard exactly but most come pretty close.

Linux 系統中,文件系統佈局與類 Unix 系統的文件佈局很類似。實際上,一個已經發布的標準, 叫作 Linux 文件系統層次標準,詳細說明了這種設計模式。不是全部Linux發行版都根據這個標準,但 大多數都是。

Next, we are going to wander around the file system ourselves to see what makes our Linux system tick. This will give you a chance to practice your navigation skills. One of the things we will discover is that many of the interesting files are in plain human- readable text. As we go about our tour, try the following:

下一步,咱們將在文件系統中漫遊,來了解 Linux 系統的工做原理。這會給你一個溫習跳轉命令的機會。 咱們會發現不少有趣的文件都是純人類可讀文本。下面旅行開始,作作如下練習:

  1. cd into a given directory
  2. List the directory contents with ls -l
  3. If you see an interesting file, determine its contents with file
  4. If it looks like it might be text, try viewing it with less

  1. cd 到給定目錄
  2. 列出目錄內容 ls -l
  3. 若是看到一個有趣的文件,用 file 命令肯定文件內容
  4. 若是文件看起來像文本,試着用 less 命令瀏覽它

Remember the copy and paste trick! If you are using a mouse, you can double click on a filename to copy it and middle click to paste it into commands.

記得複製和粘貼技巧!若是你正在使用鼠標,雙擊文件名,來複制它,而後按下鼠標中鍵,粘貼文件名到命令行中。


As we wander around, don’t be afraid to look at stuff. Regular users are largely prohibited from messing things up. That’s the system administrators job! If a command complains about something, just move on to something else. Spend some time looking around. The system is ours to explore. Remember, in Linux, there are no secrets! Table 4-4 lists just a few of the directories we can explore. Feel free to try more!

在系統中漫遊時,不要懼怕四處看看。普通用戶是很難把東西弄亂的。那是系統管理員的工做! 若是一個命令抱怨一些事情,不要管它,嘗試一下別的東西。花一些時間四處看看。 系統是咱們本身的,盡情地探究吧。記住在 Linux 中,沒有祕密存在! 表4-4僅僅列出了一些咱們能夠瀏覽的目錄。隨意嘗試更多!

Table 4-4: Directories Found On Linux Systems
Drectory Comments
/ The root directory.Where everything begins.
/bin Contains binaries (programs) that must be present for the system to boot and run.
/boot Contains the linux kernel, intial RAM disk image (for drivers needed at boot time), and the boot loader.

Interesting files:

  • /boot/grub/grub.conf or menu.lst, which are used to configure the boot loader.
  • /boot/vmlinuz,the linux kernel.
/dev This is a special directory which contains device nodes. "Everything is a file" also applies to devices. Here is where the kernel maintains a list of all the devices it understands.
/etc The /etc directory contains all of the system-wide configuration files. It also contains a collection of shell scripts which start each of the system services at boot time. Everything in this directory should be readable text.

Interesting files:While everything in /etc is interesting, here are some of my all-time favorites:

  • /etc/crontab, a file that defines when automated jobs will run.
  • /etc/fstab, a table of storage devices and their associated mount points.
  • /etc/passwd, a list of the user accounts.
/home In normal configurations, each user is given a directory in /home. Ordinary users can only write files in their home directories. This limitation protects the system from errant user activity.
/lib Contains shared library files used by the core system programs. These are similar to DLLs in Windows.
/lost+found Each formatted partition or device using a Linux file system, such as ext3, will have this directory. It is used in the case of a partial recovery from a file system corruption event. Unless something really bad has happened to your system, this directory will remain empty.
/media On modern Linux systems the /media directory will contain the mount points for removable media such USB drives, CD-ROMs, etc. that are mounted automatically at insertion.
/mnt On older Linux systems, the /mnt directory contains mount points for removable devices that have been mounted manually.
/opt The /opt directory is used to install 「optional」 software. This is mainly used to hold commercial software products that may be installed on your system.
/proc The /proc directory is special. It's not a real file system in the sense of files stored on your hard drive. Rather, it is a virtual file system maintained by the Linux kernel. The 「files」 it contains are peepholes into the kernel itself. The files are readable and will give you a picture of how the kernel sees your computer.
/root This is the home directory for the root account.
/sbin This directory contains 「system」 binaries. These are programs that perform vital system tasks that are generally reserved for the superuser.
/tmp The /tmp directory is intended for storage of temporary, transient files created by various programs. Some configurations cause this directory to be emptied each time the system is rebooted.
/usr The /usr directory tree is likely the largest one on a Linux system. It contains all the programs and support files used by regular users.
/usr/bin /usr/bin contains the executable programs installed by your Linux distribution. It is not uncommon for this directory to hold thousands of programs.
/usr/lib The shared libraries for the programs in /usr/bin.
/usr/local The /usr/local tree is where programs that are not included with your distribution but are intended for system- wide use are installed. Programs compiled from source code are normally installed in /usr/local/bin. On a newly installed Linux system, this tree exists, but it will be empty until the system administrator puts something in it.
/usr/sbin Contains more system administration programs.
/usr/share /usr/share contains all the shared data used by programs in /usr/bin. This includes things like default configuration files, icons, screen backgrounds, sound files, etc.
/usr/share/doc Most packages installed on the system will include some kind of documentation. In /usr/share/doc, we will find documentation files organized by package.
/var With the exception of /tmp and /home, the directories we have looked at so far remain relatively static, that is, their contents don't change. The /var directory tree is where data that is likely to change is stored. Various databases, spool files, user mail, etc. are located here.
/var/log /var/log contains log files, records of various system activity. These are very important and should be monitored from time to time. The most useful one is /var/log/messages. Note that for security reasons on some systems, you must be the superuser to view log files.
表 4-4: Linux 系統中的目錄
目錄 評論
/ 根目錄,萬物起源。
/bin 包含系統啓動和運行所必須的二進制程序。
/boot

包含 Linux 內核、初始 RAM 磁盤映像(用於啓動時所需的驅動)和 啓動加載程序。

有趣的文件:

  • /boot/grub/grub.conf or menu.lst, 被用來配置啓動加載程序。
  • /boot/vmlinuz,Linux 內核。
/dev 這是一個包含設備結點的特殊目錄。「一切都是文件」,也適用於設備。 在這個目錄裏,內核維護着全部設備的列表。
/etc

這個目錄包含全部系統層面的配置文件。它也包含一系列的 shell 腳本, 在系統啓動時,這些腳本會開啓每一個系統服務。這個目錄中的任何文件應該是可讀的文本文件。

有趣的文件:雖然/etc 目錄中的任何文件都有趣,但這裏只列出了一些我一直喜歡的文件:

  • /etc/crontab, 定義自動運行的任務。
  • /etc/fstab,包含存儲設備的列表,以及與他們相關的掛載點。
  • /etc/passwd,包含用戶賬號列表。
/home 在一般的配置環境下,系統會在/home 下,給每一個用戶分配一個目錄。普通用戶只能 在本身的目錄下寫文件。這個限制保護系統免受錯誤的用戶活動破壞。
/lib 包含核心系統程序所使用的共享庫文件。這些文件與 Windows 中的動態連接庫類似。
/lost+found 每一個使用 Linux 文件系統的格式化分區或設備,例如 ext3文件系統, 都會有這個目錄。當部分恢復一個損壞的文件系統時,會用到這個目錄。這個目錄應該是空的,除非文件系統 真正的損壞了。
/media 在如今的 Linux 系統中,/media 目錄會包含可移動介質的掛載點, 例如 USB 驅動器,CD-ROMs 等等。這些介質鏈接到計算機以後,會自動地掛載到這個目錄結點下。
/mnt 在早些的 Linux 系統中,/mnt 目錄包含可移動介質的掛載點。
/opt 這個/opt 目錄被用來安裝「可選的」軟件。這個主要用來存儲可能 安裝在系統中的商業軟件產品。
/proc 這個/proc 目錄很特殊。從存儲在硬盤上的文件的意義上說,它不是真正的文件系統。 相反,它是一個由 Linux 內核維護的虛擬文件系統。它所包含的文件是內核的窺視孔。這些文件是可讀的, 它們會告訴你內核是怎樣監管計算機的。
/root root 賬戶的家目錄。
/sbin 這個目錄包含「系統」二進制文件。它們是完成重大系統任務的程序,一般爲超級用戶保留。
/tmp 這個/tmp 目錄,是用來存儲由各類程序建立的臨時文件的地方。一些配置致使系統每次 從新啓動時,都會清空這個目錄。
/usr 在 Linux 系統中,/usr 目錄多是最大的一個。它包含普通用戶所須要的全部程序和文件。
/usr/bin /usr/bin 目錄包含系統安裝的可執行程序。一般,這個目錄會包含許多程序。
/usr/lib 包含由/usr/bin 目錄中的程序所用的共享庫。
/usr/local 這個/usr/local 目錄,是非系統發行版自帶程序的安裝目錄。 一般,由源碼編譯的程序會安裝在/usr/local/bin 目錄下。新安裝的 Linux 系統中會存在這個目錄, 而且在管理員安裝程序以前,這個目錄是空的。
/usr/sbin 包含許多系統管理程序。
/usr/share /usr/share 目錄包含許多由/usr/bin 目錄中的程序使用的共享數據。 其中包括像默認的配置文件、圖標、桌面背景、音頻文件等等。
/usr/share/doc 大多數安裝在系統中的軟件包會包含一些文檔。在/usr/share/doc 目錄下, 咱們能夠找到按照軟件包分類的文檔。
/var 除了/tmp 和/home 目錄以外,相對來講,目前咱們看到的目錄是靜態的,這是說, 它們的內容不會改變。/var 目錄存放的是動態文件。各類數據庫,假脫機文件, 用戶郵件等等,都位於在這裏。
/var/log 這個/var/log 目錄包含日誌文件、各類系統活動的記錄。這些文件很是重要,而且 應該時時監測它們。其中最重要的一個文件是/var/log/messages。注意,爲了系統安全,在一些系統中, 你必須是超級用戶才能查看這些日誌文件。

 

符號連接

As we look around, we are likely to see a directory listing with an entry like this:

在咱們處處查看時,咱們可能會看到一個目錄,列出像這樣的一條信息:

lrwxrwxrwx 1 root root 11 2007-08-11 07:34 libc.so.6 -> libc-2.6.so

Notice how the first letter of the listing is 「l」 and the entry seems to have two filenames? This is a special kind of a file called a symbolic link (also known as a soft link or symlink.) In most Unix-like systems it is possible to have a file referenced by multiple names. While the value of this may not be obvious, it is really a useful feature.

注意看,爲什麼這條信息第一個字符是「l」,而且有兩個文件名呢? 這是一個特殊文件,叫作符號連接(也稱爲軟連接或者 symlink )。 在大多數「類 Unix」 系統中, 有可能一個文件被多個文件名所指向。雖然這種特性的意義並不明顯,但它真的頗有用。

Picture this scenario: a program requires the use of a shared resource of some kind contained in a file named 「foo,」 but 「foo」 has frequent version changes. It would be good to include the version number in the filename so the administrator or other interested party could see what version of 「foo」 is installed. This presents a problem. If we change the name of the shared resource, we have to track down every program that might use it and change it to look for a new resource name every time a new version of the resource is installed. That doesn’t sound like fun at all.

描繪一下這樣的情景:一個程序要求使用某個包含在名爲「foo」文件中的共享資源,可是「foo」常常改變版本號。 這樣,在文件名中包含版本號,會是一個好主意,所以管理員或者其它相關方,會知道安裝了哪一個「foo」版本。 這會致使另外一個問題。若是咱們更改了共享資源的名字,那麼咱們必須跟蹤每一個可能使用了 這個共享資源的程序,當每次這個資源的新版本被安裝後,都要讓使用了它的程序去尋找新的資源名。 這聽起來很沒趣。

Here is where symbolic links save the day. Let’s say we install version 2.6 of 「foo,」 which has the filename 「foo-2.6」 and then create a symbolic link simply called 「foo」 that points to 「foo-2.6.」 This means that when a program opens the file 「foo」, it is actually opening the file 「foo-2.6」. Now everybody is happy. The programs that rely on 「foo」 can find it and we can still see what actual version is installed. When it is time to upgrade to 「foo-2.7,」 we just add the file to our system, delete the symbolic link 「foo」 and create a new one that points to the new version. Not only does this solve the problem of the version upgrade, but it also allows us to keep both versions on our machine. Imagine that 「foo-2.7」 has a bug (damn those developers!) and we need to revert to the old version. Again, we just delete the symbolic link pointing to the new version and create a new symbolic link pointing to the old version.

這就是符號連接存在至今的緣由。比方說,咱們安裝了文件 「foo」 的 2.6 版本,它的 文件名是 「foo-2.6」,而後建立了叫作 「foo」 的符號連接,這個符號連接指向 「foo-2.6」。 這意味着,當一個程序打開文件 「foo」 時,它其實是打開文件 「foo-2.6」。 如今,每一個人都很高興。依賴於 「foo」 文件的程序能找到這個文件,而且咱們能知道安裝了哪一個文件版本。 當升級到 「foo-2.7」 版本的時候,僅添加這個文件到文件系統中,刪除符號連接 「foo」, 建立一個指向新版本的符號連接。這不只解決了版本升級問題,並且還容許在系統中保存兩個不一樣的文件版本。 假想 「foo-2.7」 有個錯誤(該死的開發者!),那咱們得回到原來的版本。 同樣的操做,咱們只須要刪除指向新版本的符號連接,而後建立指向舊版本的符號連接就能夠了。

The directory listing above (from the /lib directory of a Fedora system) shows a symbolic link called 「libc.so.6」 that points to a shared library file called 「libc-2.6.so.」 This means that programs looking for 「libc.so.6」 will actually get the file 「libc-2.6.so.」 We will learn how to create symbolic links in the next chapter.

在上面列出的目錄(來自於 Fedora 的 /lib 目錄)展現了一個叫作 「libc.so.6」 的符號連接,這個符號連接指向一個 叫作 「libc-2.6.so」 的共享庫文件。這意味着,尋找文件 「libc.so.6」 的程序,實際上獲得是文件 「libc-2.6.so」。 在下一章節,咱們將學習如何創建符號連接。

硬連接

While we are on the subject of links, we need to mention that there is a second type of link called a hard link. Hard links also allow files to have multiple names, but they do it in a different way. We’ll talk more about the differences between symbolic and hard links in the next chapter.

討論到連接問題,咱們須要提一下,還有一種連接類型,叫作硬連接。硬連接一樣容許文件有多個名字, 可是硬連接以不一樣的方法來建立多個文件名。在下一章中,咱們會談到更多符號連接與硬連接之間的差別問題。

 

通配符

Before we begin using our commands, we need to talk about a shell feature that makes these commands so powerful. Since the shell uses filenames so much, it provides special characters to help you rapidly specify groups of filenames. These special characters are called wildcards. Using wildcards (which is also known as globbing) allow you to select filenames based on patterns of characters. The table below lists the wildcards and what they select:

在開始使用命令以前,咱們須要介紹一個使命令行如此強大的 shell 特性。由於 shell 頻繁地使用 文件名,shell 提供了特殊字符來幫助你快速指定一組文件名。這些特殊字符叫作通配符。 使用通配符(也以文件名代換著稱)容許你依據字符的組合模式來選擇文件名。下表列出這些通配符 以及它們所選擇的對象:

Table 5-1: Wildcards
Wildcard Meaning
* Matches any characters
? Matches any single character
[characters] Matches any character that is a member of the set characters
[!characters] Matches any character that is not a member of the set characters
[[:class:]] Matches any character that is a member of the specified class
表5-1: 通配符
通配符 意義
* 匹配任意多個字符(包括零個或一個)
? 匹配任意一個字符(不包括零個)
[characters] 匹配任意一個屬於字符集中的字符
[!characters] 匹配任意一個不是字符集中的字符
[[:class:]] 匹配任意一個屬於指定字符類中的字符

Table 5-2 lists the most commonly used character classes:

表5-2列出了最常使用的字符類:

Table 5-2: Commonly Used Character Classes
Character Class Meaning
[:alnum:] Matches any alphanumeric character
[:alpha:] Matches any alphabetic character
[:digit:] Matches any numeral
[:lower:] Matches any lowercase letter
[:upper:] Matches any uppercase letter
表5-2: 廣泛使用的字符類
字符類 意義
[:alnum:] 匹配任意一個字母或數字
[:alpha:] 匹配任意一個字母
[:digit:] 匹配任意一個數字
[:lower:] 匹配任意一個小寫字母
[:upper:] 匹配任意一個大寫字母

Using wildcards makes it possible to construct very sophisticated selection criteria for filenames. Here are some examples of patterns and what they match:

藉助通配符,爲文件名構建很是複雜的選擇標準成爲可能。下面是一些類型匹配的範例:

Table 5-3: Wildcard Examples
Pattern Matches
* All files
g* All file beginning with "g"
b*.txt Any file beginning with "b" followed by any characters and ending with ".txt"
Data??? Any file beginning with "Data" followed by exactly three characters
[abc]* Any file beginning with either an "a", a "b", or a "c"
BACKUP.[0-9][0-9][0-9] Any file beginning with "BACKUP." followed by exactly three numerals
[[:upper:]]* Any file beginning with an uppercase letter
[![:digit:]]* Any file not beginning with a numeral
*[[:lower:]123] Any file ending with a lowercase letter or the numerals "1", "2", or "3"
表5-3: 通配符範例
模式 匹配對象
* 全部文件
g* 文件名以「g」開頭的文件
b*.txt 以"b"開頭,中間有零個或任意多個字符,並以".txt"結尾的文件
Data??? 以「Data」開頭,其後緊接着3個字符的文件
[abc]* 文件名以"a","b",或"c"開頭的文件
BACKUP.[0-9][0-9][0-9] 以"BACKUP."開頭,並緊接着3個數字的文件
[[:upper:]]* 以大寫字母開頭的文件
[![:digit:]]* 不以數字開頭的文件
*[[:lower:]123] 文件名以小寫字母結尾,或以 「1」,「2」,或 「3」 結尾的文件

 

ln — 建立連接

The ln command is used to create either hard or symbolic links. It is used in one of two ways:

ln 命令既可建立硬連接,也能夠建立符號連接。能夠用其中一種方法來使用它:

ln file link

to create a hard link, and:

建立硬連接,和:

ln -s item link

to create a symbolic link where 「item」 is either a file or a directory.

建立符號連接,」item」 能夠是一個文件或是一個目錄。

硬連接

Hard links are the original Unix way of creating links; symbolic links are more modern. By default, every file has a single hard link that gives the file its name. When we create a hard link, we create an additional directory entry for a file. Hard links have two important limitations:

與更加現代的符號連接相比,硬連接是最初 Unix 建立連接的方式。每一個文件默認會有一個硬連接, 這個硬連接給予文件名字。咱們每建立一個硬連接,就爲一個文件建立了一個額外的目錄項。 硬連接有兩個重要侷限性:

  1. A hard link cannot reference a file outside its own file system. This means a link may not reference a file that is not on the same disk partition as the link itself.

  2. A hard link may not reference a directory.

  1. 一個硬連接不能關聯它所在文件系統以外的文件。這是說一個連接不能關聯 與連接自己不在同一個磁盤分區上的文件。

  2. 一個硬連接不能關聯一個目錄。

A hard link is indistinguishable from the file itself. Unlike a symbolic link, when you list a directory containing a hard link you will see no special indication of the link. When a hard link is deleted, the link is removed but the contents of the file itself continue to exist (that is, its space is not deallocated) until all links to the file are deleted. It is important to be aware of hard links because you might encounter them from time to time, but modern practice prefers symbolic links, which we will cover next.

一個硬連接和文件自己沒有什麼區別。不像符號連接,當你列出一個包含硬連接的目錄 內容時,你會看到沒有特殊的連接指示說明。當一個硬連接被刪除時,這個連接 被刪除,可是文件自己的內容仍然存在(這是說,它所佔的磁盤空間不會被從新分配), 直到全部關聯這個文件的連接都刪除掉。知道硬連接很重要,由於你可能有時 會遇到它們,但如今實際中更喜歡使用符號連接,下一步咱們會討論符號連接。

符號連接

Symbolic links were created to overcome the limitations of hard links. Symbolic links work by creating a special type of file that contains a text pointer to the referenced file or directory. In this regard, they operate in much the same way as a Windows shortcut though of course, they predate the Windows feature by many years ;-)

建立符號連接是爲了克服硬連接的侷限性。符號連接生效,是經過建立一個 特殊類型的文件,這個文件包含一個關聯文件或目錄的文本指針。在這一方面, 它們和 Windows 的快捷方式差很少,固然,符號連接早於 Windows 的快捷方式 不少年;-)

A file pointed to by a symbolic link, and the symbolic link itself are largely indistinguishable from one another. For example, if you write some something to the symbolic link, the referenced file is also written to. However when you delete a symbolic link, only the link is deleted, not the file itself. If the file is deleted before the symbolic link, the link will continue to exist, but will point to nothing. In this case, the link is said to be broken. In many implementations, the ls command will display broken links in a distinguishing color, such as red, to reveal their presence.

一個符號連接指向一個文件,並且這個符號連接自己與其它的符號連接幾乎沒有區別。 例如,若是你往一個符號連接裏面寫入東西,那麼相關聯的文件也被寫入。然而, 當你刪除一個符號連接時,只有這個連接被刪除,而不是文件自身。若是先於符號連接 刪除文件,這個連接仍然存在,可是不指向任何東西。在這種狀況下,這個連接被稱爲 壞連接。在許多實現中,ls 命令會以不一樣的顏色展現壞連接,好比說紅色,來顯示它們 的存在。

The concept of links can seem very confusing, but hang in there. We’re going to try all this stuff and it will, hopefully, become clear.

關於連接的概念,看起來很迷惑,但不要膽怯。咱們將要試着練習 這些命令,但願,它變得清晰起來。

 

練習:

建立硬連接

Now we’ll try some links. First the hard links. We’ll create some links to our data file like so:

如今,咱們試着建立連接。首先是硬連接。咱們建立一些關聯咱們 數據文件的連接:

[me@linuxbox playground]$ ln fun fun-hard
[me@linuxbox playground]$ ln fun dir1/fun-hard
[me@linuxbox playground]$ ln fun dir2/fun-hard

So now we have four instances of the file 「fun」. Let’s take a look our playground directory:

因此如今,咱們有四個文件」fun」的實例。看一下目錄 playground 中的內容:

[me@linuxbox playground]$ ls -l
total 16
drwxrwxr-x 2 me  me 4096 2008-01-14 16:17 dir1
drwxrwxr-x 2 me  me 4096 2008-01-14 16:17 dir2
-rw-r--r-- 4 me  me 1650 2008-01-10 16:33 fun
-rw-r--r-- 4 me  me 1650 2008-01-10 16:33 fun-hard

One thing you notice is that the second field in the listing for fun and fun-hard both contain a 「4」 which is the number of hard links that now exist for the file. You’ll remember that a file will always have at least one because the file’s name is created by a link. So, how do we know that fun and fun-hard are, in fact, the same file? In this case, ls is not very helpful. While we can see that fun and fun-hard are both the same size (field 5), our listing provides no way to be sure. To solve this problem, we’re going to have to dig a little deeper.

注意到一件事,列表中,文件 fun 和 fun-hard 的第二個字段是」4」,這個數字 是文件」fun」的硬連接數目。你要記得一個文件至少有一個硬連接,由於文件 名就是由連接建立的。那麼,咱們怎樣知道實際上 fun 和 fun-hard 是同一個文件呢? 在這個例子裏,ls 不是頗有用。雖然咱們可以看到 fun 和 fun-hard 文件大小同樣 (第五字段),但咱們的列表沒有提供可靠的信息來肯定(這兩個文件同樣)。 爲了解決這個問題,咱們更深刻的研究一下。

When thinking about hard links, it is helpful to imagine that files are made up of two parts: the data part containing the file’s contents and the name part which holds the file’s name. When we create hard links, we are actually creating additional name parts that all refer to the same data part. The system assigns a chain of disk blocks to what is called an inode, which is then associated with the name part. Each hard link therefore refers to a specific inode containing the file’s contents.

當考慮到硬連接的時候,咱們能夠假設文件由兩部分組成:包含文件內容的數據部分和持有文件名的名字部分 ,這將有助於咱們理解這個概念。當咱們建立文件硬連接的時候,其實是爲文件建立了額外的名字部分, 而且這些名字都關聯到相同的數據部分。這時系統會分配一連串的磁盤塊給所謂的索引節點,而後索引節點與文 件名字部分相關聯。所以每個硬連接都關係到一個具體的包含文件內容的索引節點。

The ls command has a way to reveal this information. It is invoked with the 「-i」 option:

ls 命令有一種方法,來展現(文件索引節點)的信息。在命令中加上」-i」選項:

[me@linuxbox playground]$ ls -li
total 16
12353539 drwxrwxr-x 2 me  me 4096  2008-01-14  16:17  dir1
12353540 drwxrwxr-x 2 me  me 4096  2008-01-14  16:17  dir2
12353538 -rw-r--r-- 4 me  me 1650  2008-01-10  16:33  fun
12353538 -rw-r--r-- 4 me  me 1650  2008-01-10  16:33  fun-hard

In this version of the listing, the first field is the inode number and, as we can see, both fun and fun-hard share the same inode number, which confirms they are the same file.

在這個版本的列表中,第一字段表示文件索引節點號,正如咱們所見到的, fun 和 fun-hard 共享同樣的索引節點號,這就證明這兩個文件是同一個文件。

建立符號連接

Symbolic links were created to overcome the two disadvantages of hard links: hard links cannot span physical devices and hard links cannot reference directories, only files. Symbolic links are a special type of file that contains a text pointer to the target file or directory.

創建符號連接的目的是爲了克服硬連接的兩個缺點:硬連接不能跨越物理設備, 硬連接不能關聯目錄,只能是文件。符號連接是文件的特殊類型,它包含一個指向 目標文件或目錄的文本指針。

Creating symbolic links is similar to creating hard links:

符號連接的創建過程類似於建立硬連接:

[me@linuxbox playground]$ ln -s fun fun-sym
[me@linuxbox playground]$ ln -s ../fun dir1/fun-sym
[me@linuxbox playground]$ ln -s ../fun dir2/fun-sym

The first example is pretty straightforward, we simply add the 「-s」 option to create a symbolic link rather than a hard link. But what about the next two? Remember, when we create a symbolic link, we are creating a text description of where the target file is relative to the symbolic link. It’s easier to see if we look at the ls output:

第一個例子至關直接,在 ln 命令中,簡單地加上」-s」選項就能夠建立一個符號連接, 而不是一個硬連接。下面兩個例子又是怎樣呢? 記住,當咱們建立一個符號連接 的時候,會創建一個目標文件在哪裏和符號連接有關聯的文本描述。若是咱們看看 ls 命令的輸出結果,比較容易理解。

[me@linuxbox playground]$ ls -l dir1
total 4
-rw-r--r-- 4 me  me 1650 2008-01-10 16:33 fun-hard
lrwxrwxrwx 1 me  me    6 2008-01-15 15:17 fun-sym -> ../fun

The listing for fun-sym in dir1 shows that is it a symbolic link by the leading 「l」 in the first field and that it points to 「../fun」, which is correct. Relative to the location of fun-sym, fun is in the directory above it. Notice too, that the length of the symbolic link file is 6, the number of characters in the string 「../fun」 rather than the length of the file to which it is pointing.

目錄 dir1 中,fun-sym 的列表說明了它是一個符號連接,經過在第一字段中的首字符」l」 可知,而且它還指向」../fun」,也是正確的。相對於 fun-sym 的存儲位置,fun 在它的 上一個目錄。同時注意,符號連接文件的長度是6,這是字符串」../fun」所包含的字符數, 而不是符號連接所指向的文件長度。

When creating symbolic links, you can either use absolute pathnames:

當創建符號連接時,你既可使用絕對路徑名:

ln -s /home/me/playground/fun dir1/fun-sym

or relative pathnames, as we did in our earlier example. Using relative pathnames is more desirable because it allows a directory containing symbolic links to be renamed and/or moved without breaking the links.

也可用相對路徑名,正如前面例題所展現的。使用相對路徑名更使人滿意, 由於它容許一個包含符號連接的目錄重命名或移動,而不會破壞連接。

In addition to regular files, symbolic links can also reference directories:

除了普通文件,符號連接也能關聯目錄:




[me@linuxbox playground]$ ln -s dir1 dir1-sym [me@linuxbox playground]$ ls -l total 16 ...省略

到底什麼是命令?

A command can be one of four different things:

命令能夠是下面四種形式之一:

  1. An executable program like all those files we saw in /usr/bin. Within this category, programs can be compiled binaries such as programs written in C and C++, or programs written in scripting languages such as the shell, perl, python, ruby, etc.

  2. A command built into the shell itself. bash supports a number of commands internally called shell builtins. The cd command, for example, is a shell builtin.

  3. A shell function. These are miniature shell scripts incorporated into the environment. We will cover configuring the environment and writing shell functions in later chapters, but for now, just be aware that they exist.

  4. An alias. Commands that we can define ourselves, built from other commands.

  1. 是一個可執行程序,就像咱們所看到的位於目錄/usr/bin 中的文件同樣。 這一類程序能夠是用諸如 C 和 C++語言寫成的程序編譯的二進制文件, 也能夠是由諸如shell,perl,python,ruby等等腳本語言寫成的程序 。

  2. 是一個內建於 shell 自身的命令。bash 支持若干命令,內部叫作 shell 內部命令 (builtins)。例如,cd 命令,就是一個 shell 內部命令。

  3. 是一個 shell 函數。這些是小規模的 shell 腳本,它們混合到環境變量中。 在後續的章節裏,咱們將討論配置環境變量以及書寫 shell 函數。可是如今, 僅僅意識到它們的存在就能夠了。

  4. 是一個命令別名。咱們能夠定義本身的命令,創建在其它命令之上。

識別命令

It is often useful to know exactly which of the four kinds of commands is being used and Linux provides a couple of ways to find out.

這常常頗有用,能確切地知道正在使用四類命令中的哪一類。Linux 提供了一對方法來 弄明白命令類型。

type - 顯示命令的類型

The type command is a shell builtin that displays the kind of command the shell will execute, given a particular command name. It works like this:

type 命令是 shell 內部命令,它會顯示命令的類別,給出一個特定的命令名(作爲參數)。 它像這樣工做:

type command

Where 「command」 is the name of the command you want to examine. Here are some examples:

「command」是你要檢測的命令名。這裏有些例子:

[me@linuxbox ~]$ type type
type is a shell builtins
[me@linuxbox ~]$ type ls
ls is aliased to `ls --color=tty`
[me@linuxbox ~]$ type cp
cp is /bin/cp

Here we see the results for three different commands. Notice that the one for ls (taken from a Fedora system) and how the ls command is actually an alias for the ls command with the 「--color=tty」 option added. Now we know why the output from ls is displayed in color!

咱們看到這三個不一樣命令的檢測結果。注意,ls 命令(在 Fedora 系統中)的檢查結果,ls 命令實際上 是 ls 命令加上選項」--color=tty」的別名。如今咱們知道爲何 ls 的輸出結果是有顏色的!

 

which - 顯示一個可執行程序的位置

Sometimes there is more than one version of an executable program installed on a system. While this is not very common on desktop systems, it’s not unusual on large servers. To determine the exact location of a given executable, the which command is used:

有時候在一個操做系統中,不僅安裝了可執行程序的一個版本。雖然在桌面系統中這並不廣泛, 但在大型服務器中卻很日常。爲了肯定所給定的執行程序的準確位置,使用 which 命令:

[me@linuxbox ~]$ which ls
/bin/ls

which only works for executable programs, not builtins nor aliases that are substitutes for actual executable programs. When we try to use which on a shell builtin, for example, cd, we either get no response or an error message:

這個命令只對可執行程序有效,不包括內建命令和命令別名,別名是真正的可執行程序的替代物。 當咱們試着使用 shell 內建命令時,例如,cd 命令,咱們或者得不到迴應,或者是個錯誤信息:

[me@linuxbox ~]$ which cd
/usr/bin/which: no cd in
(/opt/jre1.6.0_03/bin:/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/opt/jre1
.6.0_03/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:/home/me/bin)

which is a fancy way of saying 「command not found.」

說「命令沒有找到」,真是很奇特。

 

用別名(alias)建立你本身的命令

Now for our very first experience with programming! We will create a command of our own using the alias command. But before we start, we need to reveal a small command line trick. It’s possible to put more than one command on a line by separating each command with a semicolon character. It works like this:

如今是時候,感覺第一次編程經歷了!咱們將用 alias 命令建立咱們本身的命令。但在 開始以前,咱們須要展現一個命令行小技巧。能夠把多個命令放在同一行上,命令之間 用」;」分開。它像這樣工做:

command1; command2; command3...

Here’s the example we will use:

咱們會用到下面的例子:

[me@linuxbox ~]$ cd /usr; ls; cd -
bin  games    kerberos  lib64    local  share  tmp
...
[me@linuxbox ~]$

As we can see, we have combined three commands on one line. First we change directory to /usr then list the directory and finally return to the original directory (by using ‘cd -‘) so we end up where we started. Now let’s turn this sequence into a new command using alias. The first thing we have to do is dream up a name for our new command. Let’s try 「test」. Before we do that, it would be a good idea to find out if the name 「test」 is already being used. To find out, we can use the type command again:

正如咱們看到的,咱們在一行上聯合了三個命令。首先更改目錄到/usr,而後列出目錄 內容,最後回到原始目錄(用命令」cd -「),結束在開始的地方。如今,經過 alias 命令 把這一串命令轉變爲一個命令。咱們要作的第一件事就是爲咱們的新命令構想一個名字。 比方說」test」。在使用」test」以前,查明是否」test」命令名已經存在系統中,是個很不錯 的主意。爲了查清此事,可使用 type 命令:

[me@linuxbox ~]$ type test
test is a shell builtin

Oops! The name 「test」 is already taken. Let’s try 「foo」:

哦!」test」名字已經被使用了。試一下」foo」:

[me@linuxbox ~]$ type foo
bash: type: foo: not found

Great! 「foo」 is not taken. So let’s create our alias:

太棒了!」foo」還沒被佔用。建立命令別名:

[me@linuxbox ~]$ alias foo='cd /usr; ls; cd -'

Notice the structure of this command:

注意命令結構:

alias name='string'

After the command 「alias」 we give alias a name followed immediately (no whitespace allowed) by an equals sign, followed immediately by a quoted string containing the meaning to be assigned to the name. After we define our alias, it can be used anywhere the shell would expect a command. Let’s try it:

在命令」alias」以後,輸入「name」,緊接着(沒有空格)是一個等號,等號以後是 一串用引號引發的字符串,字符串的內容要賦值給 name。咱們定義了別名以後, 這個命令別名可使用在任何地方。試一下:

[me@linuxbox ~]$ foo
bin   games   kerberos  lib64    local   share  tmp
...
[me@linuxbox ~]$

We can also use the type command again to see our alias:

咱們也可使用 type 命令來查看咱們的別名:

[me@linuxbox ~]$ type foo
foo is aliased to `cd /usr; ls ; cd -'

To remove an alias, the unalias command is used, like so:

刪除別名,使用 unalias 命令,像這樣:

[me@linuxbox ~]$ unalias foo
[me@linuxbox ~]$ type foo
bash: type: foo: not found

While we purposefully avoided naming our alias with an existing command name, it is not uncommon to do so. This is often done to apply a commonly desired option to each invocation of a common command. For instance, we saw earlier how the ls command is often aliased to add color support:

雖然咱們有意避免使用已經存在的命令名來命名咱們的別名,但這是常作的事情。一般, 會把一個廣泛用到的選項加到一個常用的命令後面。例如,以前見到的 ls 命令,會 帶有色彩支持:

[me@linuxbox ~]$ type ls
ls is aliased to 'ls --color=tty'

To see all the aliases defined in the environment, use the alias command without arguments. Here are some of the aliases defined by default on a Fedora system. Try and figure out what they all do:

要查看全部定義在系統環境中的別名,使用不帶參數的 alias 命令。下面在 Fedora 系統中 默認定義的別名。試着弄明白,它們是作什麼的:

[me@linuxbox ~]$ alias
alias l.='ls -d .* --color=tty'
...

There is one tiny problem with defining aliases on the command line. They vanish when your shell session ends. In a later chapter, we will see how to add our own aliases to the files that establish the environment each time we log on, but for now, enjoy the fact that we have taken our first, albeit tiny, step into the world of shell programming!

在命令行中定義別名有點兒小問題。當你的 shell 會話結束時,它們會消失。隨後的章節裏, 咱們會了解怎樣把本身的別名添加到文件中去,每次咱們登陸系統,這些文件會創建系統環境。 如今,好好享受咱們剛經歷過的,步入 shell 編程世界的第一步吧,雖然微小。

標準輸入、輸出和錯誤

Many of the programs that we have used so far produce output of some kind. This output often consists of two types. First, we have the program’s results; that is, the data the program is designed to produce, and second, we have status and error messages that tell us how the program is getting along. If we look at a command like ls, we can see that it displays its results and its error messages on the screen.

到目前爲止,咱們用到的許多程序都會產生某種輸出。這種輸出,常常由兩種類型組成。 第一,程序運行結果;這是說,程序要完成的功能。第二,咱們獲得狀態和錯誤信息, 這些告訴咱們程序進展。若是咱們觀察一個命令,像 ls,會看到它的運行結果和錯誤信息 顯示在屏幕上。

Keeping with the Unix theme of 「everything is a file,」 programs such as ls actually send their results to a special file called standard output (often expressed as stdout) and their status messages to another file called standard error (stderr). By default, both standard output and standard error are linked to the screen and not saved into a disk file. In addition, many programs take input from a facility called standard input (stdin) which is, by default, attached to the keyboard.

與 Unix 主題「任何東西都是一個文件」保持一致,程序,比方說 ls,實際上把他們的運行結果 輸送到一個叫作標準輸出的特殊文件(常常用 stdout 表示),而它們的狀態信息則送到另外一個 叫作標準錯誤的文件(stderr)。默認狀況下,標準輸出和標準錯誤都鏈接到屏幕,而不是 保存到磁盤文件。除此以外,許多程序從一個叫作標準輸入(stdin)的設備獲得輸入,默認狀況下, 標準輸入鏈接到鍵盤。

I/O redirection allows us to change where output goes and where input comes from. Normally, output goes to the screen and input comes from the keyboard, but with I/O redirection, we can change that.

I/O 重定向容許咱們更改輸出地點和輸入來源。通常地,輸出送到屏幕,輸入來自鍵盤, 可是經過 I/O 重定向,咱們能夠作出改變。

標準輸出重定向

I/O redirection allows us to redefine where standard output goes. To redirect standard output to another file besides the screen, we use the 「>」 redirection operator followed by the name of the file. Why would we want to do this? It’s often useful to store the output of a command in a file. For example, we could tell the shell to send the output of the ls command to the file ls-output.txt instead of the screen:

I/O 重定向容許咱們來重定義標準輸出的地點。咱們使用 「>」 重定向符後接文件名將標準輸出重定向到除屏幕 之外的另外一個文件。爲何咱們要這樣作呢?由於有時候把一個命令的運行結果存儲到 一個文件頗有用處。例如,咱們能夠告訴 shell 把 ls 命令的運行結果輸送到文件 ls-output.txt 中去, 由文件代替屏幕。

[me@linuxbox ~]$ ls -l /usr/bin > ls-output.txt

Here, we created a long listing of the /usr/bin directory and sent the results to the file ls-output.txt. Let’s examine the redirected output of the command:

這裏,咱們建立了一個長長的目錄/usr/bin 列表,而且輸送程序運行結果到文件 ls-output.txt 中。 咱們檢查一下重定向的命令輸出結果:

[me@linuxbox ~]$ ls -l ls-output.txt
-rw-rw-r-- 1   me   me    167878 2008-02-01 15:07 ls-output.txt

Good; a nice, large, text file. If we look at the file with less, we will see that the file ls-output.txt does indeed contain the results from our ls command:

好;一個不錯的大型文本文件。若是咱們用 less 閱讀器來查看這個文件,咱們會看到文件 ls-output.txt 的確包含 ls 命令的執行結果。

[me@linuxbox ~]$ less ls-output.txt

Now, let’s repeat our redirection test, but this time with a twist. We’ll change the name of the directory to one that does not exist:

如今,重複咱們的重定向測試,但此次有改動。咱們把目錄換成一個不存在的目錄。

[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt
ls: cannot access /bin/usr: No such file or directory

We received an error message. This makes sense since we specified the non-existent directory /bin/usr, but why was the error message displayed on the screen rather than being redirected to the file ls-output.txt? The answer is that the ls program does not send its error messages to standard output. Instead, like most well-written Unix programs, it sends its error messages to standard error. Since we only redirected standard output and not standard error, the error message was still sent to the screen. We’ll see how to redirect standard error in just a minute, but first, let’s look at what happened to our output file:

咱們收到一個錯誤信息。這講得通,由於咱們指定了一個不存在的目錄/bin/usr, 可是爲何這條錯誤信息顯示在屏幕上而不是被重定向到文件 ls-output.txt?答案是, ls 程序不把它的錯誤信息輸送到標準輸出。反而,像許多寫得不錯的 Unix 程序,ls 把 錯誤信息送到標準錯誤。由於咱們只是重定向了標準輸出,而沒有重定向標準錯誤, 因此錯誤信息被送到屏幕。立刻,咱們將知道怎樣重定向標準錯誤,可是首先看一下 咱們的輸出文件發生了什麼事情。

me@linuxbox ~]$ ls -l ls-output.txt
-rw-rw-r-- 1 me   me    0 2008-02-01 15:08 ls-output.txt

The file now has zero length! This is because, when we redirect output with the 「>」 redirection operator, the destination file is always rewritten from the beginning. Since our ls command generated no results and only an error message, the redirection operation started to rewrite the file and then stopped because of the error, resulting in its truncation. In fact, if we ever need to actually truncate a file (or create a new, empty file) we can use a trick like this:

文件長度爲零!這是由於,當咱們使用 「>」 重定向符來重定向輸出結果時,目標文件老是從開頭被重寫。 由於咱們 ls 命令沒有產生運行結果,只有錯誤信息,重定向操做開始重寫文件,而後 因爲錯誤而中止,致使文件內容清空。事實上,若是咱們須要清空一個文件內容(或者建立一個 新的空文件),可使用這樣的技巧:

[me@linuxbox ~]$ > ls-output.txt

Simply using the redirection operator with no command preceding it will truncate an existing file or create a new, empty file.

簡單地使用重定向符,沒有命令在它以前,這會清空一個已存在文件的內容或是 建立一個新的空文件。

So, how can we append redirected output to a file instead of overwriting the file from the beginning? For that, we use the 「>>」 redirection operator, like so:

因此,怎樣才能把重定向結果追加到文件內容後面,而不是從開頭重寫文件?爲了這個目的, 咱們使用」>>「重定向符,像這樣:

[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt

Using the 「>>」 operator will result in the output being appended to the file. If the file does not already exist, it is created just as though the 「>」 operator had been used. Let’s put it to the test:

使用」>>「操做符,將致使輸出結果添加到文件內容以後。若是文件不存在,文件會 被建立,就如使用了」>」操做符。把它放到測試中:

[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l ls-output.txt
-rw-rw-r-- 1 me   me    503634 2008-02-01 15:45 ls-output.txt

We repeated the command three times resulting in an output file three times as large.

咱們重複執行命令三次,致使輸出文件大小是原來的三倍。

標準錯誤重定向

Redirecting standard error lacks the ease of a dedicated redirection operator. To redirect standard error we must refer to its file descriptor. A program can produce output on any of several numbered file streams. While we have referred to the first three of these file streams as standard input, output and error, the shell references them internally as file descriptors zero, one and two, respectively. The shell provides a notation for redirecting files using the file descriptor number. Since standard error is the same as file descriptor number two, we can redirect standard error with this notation:

標準錯誤重定向沒有專用的重定向操做符。爲了重定向標準錯誤,咱們必須參考其文件描述符。 一個程序能夠在幾個編號的文件流中的任一個上產生輸出。雖然咱們已經將這些文件流的前 三個稱做標準輸入、輸出和錯誤,shell 內部分別將其稱爲文件描述符0、1和2。shell 使用文件描述符提供 了一種表示法來重定向文件。由於標準錯誤和文件描述符2同樣,咱們用這種 表示法來重定向標準錯誤:

[me@linuxbox ~]$ ls -l /bin/usr 2> ls-error.txt

The file descriptor 「2」 is placed immediately before the redirection operator to perform the redirection of standard error to the file ls-error.txt.

文件描述符」2」,緊挨着放在重定向操做符以前,來執行重定向標準錯誤到文件 ls-error.txt 任務。

重定向標準輸出和錯誤到同一個文件

There are cases in which we may wish to capture all of the output of a command to a single file. To do this, we must redirect both standard output and standard error at the same time. There are two ways to do this. First, the traditional way, which works with old versions of the shell:

可能有這種狀況,咱們但願捕捉一個命令的全部輸出到一個文件。爲了完成這個,咱們 必須同時重定向標準輸出和標準錯誤。有兩種方法來完成任務。第一個,傳統的方法, 在舊版本 shell 中也有效:

[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt 2>&1

Using this method, we perform two redirections. First we redirect standard output to the file ls-output.txt and then we redirect file descriptor two (standard error) to file descriptor one (standard output) using the notation 2>&1.

使用這種方法,咱們完成兩個重定向。首先重定向標準輸出到文件 ls-output.txt,而後 重定向文件描述符2(標準錯誤)到文件描述符1(標準輸出)使用表示法2>&1。


Notice that the order of the redirections is significant. The redirection of standard error must always occur after redirecting standard output or it doesn’t work. In the example above,

注意重定向的順序安排很是重要。標準錯誤的重定向必須老是出如今標準輸出 重定向以後,要否則它不起做用。上面的例子,

>ls-output.txt 2>&1

redirects standard error to the file ls-output.txt, but if the order is changed to

重定向標準錯誤到文件 ls-output.txt,可是若是命令順序改成:

2>&1 >ls-output.txt

standard error is directed to the screen.

則標準錯誤定向到屏幕。


Recent versions of bash provide a second, more streamlined method for performing this combined redirection:

如今的 bash 版本提供了第二種方法,更精簡合理的方法來執行這種聯合的重定向。

[me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt

In this example, we use the single notation &> to redirect both standard output and standard error to the file ls-output.txt.

在這個例子裏面,咱們使用單單一個表示法 &> 來重定向標準輸出和錯誤到文件 ls-output.txt。

處理不須要的輸出

Sometimes 「silence is golden,」 and we don’t want output from a command, we just want to throw it away. This applies particularly to error and status messages. The system provides a way to do this by redirecting output to a special file called 「/dev/null」. This file is a system device called a bit bucket which accepts input and does nothing with it. To suppress error messages from a command, we do this:

有時候「沉默是金」,咱們不想要一個命令的輸出結果,只想把它們扔掉。這種狀況 尤爲適用於錯誤和狀態信息。系統經過重定向輸出結果到一個叫作」/dev/null」的特殊文件, 爲咱們提供瞭解決問題的方法。這個文件是系統設備,叫作位存儲桶,它能夠 接受輸入,而且對輸入不作任何處理。爲了隱瞞命令錯誤信息,咱們這樣作:





[me@linuxbox ~]$ ls -l /bin/usr 2> /dev/null

波浪線展開

As you may recall from our introduction to the cd command, the tilde character (「~」) has a special meaning. When used at the beginning of a word, it expands into the name of the home directory of the named user, or if no user is named, the home directory of the current user:

可能你從咱們對 cd 命令的介紹中回想起來,波浪線字符(「~」)有特殊的含義。當它用在 一個單詞的開頭時,它會展開成指定用戶的家目錄名,若是沒有指定用戶名,則展開成當前用戶的家目錄:




[me@linuxbox ~]$ echo ~ /home/me

算術表達式展開

The shell allows arithmetic to be performed by expansion. This allow us to use the shell prompt as a calculator:

shell 在展開中執行算數表達式。這容許咱們把 shell 提示看成計算器來使用:

[me@linuxbox ~]$ echo $((2 + 2))
4

Arithmetic expansion uses the form:

算術表達式展開使用這種格式:

$((expression))

where expression is an arithmetic expression consisting of values and arithmetic operators.

(以上括號中的)表達式是指算術表達式,它由數值和算術操做符組成。

Arithmetic expansion only supports integers (whole numbers, no decimals), but can perform quite a number of different operations. Here are a few of the supported operators:

算術表達式只支持整數(所有是數字,不帶小數點),可是能執行不少不一樣的操做。這裏是 一些它支持的操做符:

Table 8-1: Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division(but remember, since expansion only supports integer arithmetic, results are integers.)
% Modulo, which simply means, "remainder".
** Exponentiation
表 8-1: 算術操做符
操做符 說明
+
-
*
/ 除(可是記住,由於展開只是支持整數除法,因此結果是整數。)
% 取餘,只是簡單的意味着,「餘數」
** 取冪

Spaces are not significant in arithmetic expressions and expressions may be nested. For example, to multiply five squared by three:

在算術表達式中空格並不重要,而且表達式能夠嵌套。例如,5的平方乘以3:

[me@linuxbox ~]$ echo $(($((5**2)) * 3))
75

Single parentheses may be used to group multiple subexpressions. With this technique, we can rewrite the example above and get the same result using a single expansion instead of two:

一對括號能夠用來把多個子表達式括起來。經過這個技術,咱們能夠重寫上面的例子, 同時用一個展開代替兩個,來獲得同樣的結果:

[me@linuxbox ~]$ echo $(((5**2) * 3))
75

Here is an example using the division and remainder operators. Notice the effect of integer division:

這是一個使用除法和取餘操做符的例子。注意整數除法的結果:




[me@linuxbox ~]$ echo Five divided by two equals $((5/2)) Five divided by two equals 2 [me@linuxbox ~]$ echo with $((5%2)) left over. with 1 left over.

花括號展開

Perhaps the strangest expansion is called brace expansion. With it, you can create multiple text strings from a pattern containing braces. Here’s an example:

可能最奇怪的展開是花括號展開。經過它,你能夠從一個包含花括號的模式中 建立多個文本字符串。這是一個例子:

[me@linuxbox ~]$ echo Front-{A,B,C}-Back
Front-A-Back Front-B-Back Front-C-Back

Patterns to be brace expanded may contain a leading portion called a preamble and a trailing portion called a postscript. The brace expression itself may contain either a comma-separated list of strings, or a range of integers or single characters. The pattern may not contain embedded whitespace. Here is an example using a range of integers:

花括號展開模式可能包含一個開頭部分叫作報頭,一個結尾部分叫作附言。花括號表達式自己可 能包含一個由逗號分開的字符串列表,或者一個整數區間,或者單個的字符的區間。這種模式不能 嵌入空白字符。這個例子中使用了一個整數區間:

[me@linuxbox ~]$ echo Number_{1..5}
Number_1  Number_2  Number_3  Number_4  Number_5

A range of letters in reverse order:

倒序排列的字母區間:

[me@linuxbox ~]$ echo {Z..A}
Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Brace expansions may be nested:

花括號展開能夠嵌套:

[me@linuxbox ~]$ echo a{A{1,2},B{3,4}}b
aA1b aA2b aB3b aB4b

So what is this good for? The most common application is to make lists of files or directories to be created. For example, if we were photographers and had a large collection of images that we wanted to organize into years and months, the first thing we might do is create a series of directories named in numeric 「Year-Month」 format. This way, the directory names will sort in chronological order. We could type out a complete list of directories, but that’s a lot of work and it’s error-prone too. Instead, we could do this:

那麼這對什麼有好處呢?最多見的應用是,建立一系列的文件或目錄列表。例如, 若是咱們是攝影師,有大量的相片。咱們想把這些相片按年月前後組織起來。首先, 咱們要建立一系列以數值」年-月」形式命名的目錄。經過這種方式,可使目錄名按照 年代順序排列。咱們能夠手動鍵入整個目錄列表,可是工做量太大了,而且易於出錯。 反之,咱們能夠這樣作:

[me@linuxbox ~]$ mkdir Pics
[me@linuxbox ~]$ cd Pics
[me@linuxbox Pics]$ mkdir {2007..2009}-0{1..9} {2007..2009}-{10..12}
[me@linuxbox Pics]$ ls
2007-01 2007-07 2008-01 2008-07 2009-01 2009-07
2007-02 2007-08 2008-02 2008-08 2009-02 2009-08
2007-03 2007-09 2008-03 2008-09 2009-03 2009-09
2007-04 2007-10 2008-04 2008-10 2009-04 2009-10
2007-05 2007-11 2008-05 2008-11 2009-05 2009-11
2007-06 2007-12 2008-06 2008-12 2009-06 2009-12

Pretty slick!

棒極了!

 

鍵盤高級操做技巧

移動光標

The following table lists the keys used to move the cursor:

下表列出了移動光標所使用的按鍵:

Table 9-1: Cursor Movement Commands
Key Action
Ctrl-a Move cursor to the beginning of the line.
Ctrl-e Move cursor to the end of the line.
Ctrl-f Move cursor forward one character;same as the right arrow key.
Ctrl-b Move cursor backward one character;same as the left arrow key.
Alt-f Move cursor forward one word.
Alt-b Move cursor backward one word.
Ctrl-l Clear the screen and move the cursor to the top left corner. The clear command does the same thing.
表9-1: 光標移動命令
按鍵 行動
Ctrl-a 移動光標到行首。
Ctrl-e 移動光標到行尾。
Ctrl-f 光標前移一個字符;和右箭頭做用同樣。
Ctrl-b 光標後移一個字符;和左箭頭做用同樣。
Alt-f 光標前移一個字。
Alt-b 光標後移一個字。
Ctrl-l 清空屏幕,移動光標到左上角。clear 命令完成一樣的工做。

修改文本

Table 9-2 lists keyboard commands that are used to edit characters on the command line.

表9-2列出了鍵盤命令,這些命令用來在命令行中編輯字符。

Table 9-2: Text Editing Commands
Key Action
Ctrl-d Delete the character at the cursor location
Ctrl-t Transpose(exchange)the character at the cursor location with the one preceding it.
Alt-t Transpose the word at the cursor location with the one preceding it.
Alt-l Convert the characters from the cursor location to the end of the word to lowercase.
Alt-u Convert the characters from the cursor location to the end of the word to uppercase.
表9-2: 文本編輯命令
按鍵 行動
Ctrl-d 刪除光標位置的字符。
Ctrl-t 光標位置的字符和光標前面的字符互換位置。
Alt-t 光標位置的字和其前面的字互換位置。
Alt-l 把從光標位置到字尾的字符轉換成小寫字母。
Alt-u 把從光標位置到字尾的字符轉換成大寫字母。

剪切和粘貼文本

The Readline documentation uses the terms killing and yanking to refer to what we would commonly call cutting and pasting. Items that are cut are stored in a buffer called the kill-ring.

Readline 的文檔使用術語 killing 和 yanking 來指咱們日常所說的剪切和粘貼。 剪切下來的本文被存儲在一個叫作剪切環(kill-ring)的緩衝區中。

Table 9-3: Cut And Paste Commands
Key Action
Ctrl-k Kill text from the cursor location to the end of line.
Ctrl-u Kill text from the cursor location to the beginning of the line.
Alt-d Kill text from the cursor location to the end of the current word.
Alt-Backspace Kill text from the cursor location to the beginning of the word. If the cursor is at the beginning of a word, kill the previous word.
Ctrl-y Yank text from the kill-ring and insert it at the cursor location.
表9-3: 剪切和粘貼命令
按鍵 行動
Ctrl-k 剪切從光標位置到行尾的文本。
Ctrl-u 剪切從光標位置到行首的文本。
Alt-d 剪切從光標位置到詞尾的文本。
Alt-Backspace 剪切從光標位置到詞頭的文本。若是光標在一個單詞的開頭,剪切前一個單詞。
Ctrl-y 把剪切環中的文本粘貼到光標位置。

 

查看進程

The most commonly used command to view processes (there are several) is ps. The ps program has a lot of options, but in it simplest form it is used like this:

查看進程,最常使用地命令(有幾個命令)是 ps(process status)。ps 程序有許多選項,它最簡單地使用形式是這樣的:

[me@linuxbox ~]$ ps
PID TTY           TIME CMD
5198 pts/1    00:00:00 bash
10129 pts/1   00:00:00 ps

The result in this example lists two processes, process 5198 and process 10129, which are bash and ps respectively. As we can see, by default, ps doesn’t show us very much, just the processes associated with the current terminal session. To see more, we need to add some options, but before we do that, let’s look at the other fields produced by ps. TTY is short for 「Teletype,」 and refers to the controlling terminal for the process. Unix is showing its age here. The TIME field is the amount of CPU time consumed by the process. As we can see, neither process makes the computer work very hard.

上例中,列出了兩個進程,進程 5198 和進程 10129,各自表明命令 bash 和 ps。正如咱們所看到的, 默認狀況下,ps 不會顯示不少進程信息,只是列出與當前終端會話相關的進程。爲了獲得更多信息, 咱們須要加上一些選項,可是在這樣作以前,咱們先看一下 ps 命令運行結果的其它字段。 TTY 是 「Teletype」(直譯電傳打字機) 的簡寫,是指進程的控制終端。TTY足足顯示了 Unix 的年代久遠。TIME 字段表示 進程所消耗的 CPU 時間數量。正如咱們所看到的,這兩個進程使計算機工做起來很輕鬆。

If we add an option, we can get a bigger picture of what the system is doing:

若是給 ps 命令加上選項,咱們能夠獲得更多關於系統運行狀態的信息:

[me@linuxbox ~]$ ps x
PID TTY   STAT   TIME COMMAND
2799 ?    Ssl    0:00 /usr/libexec/bonobo-activation-server –ac
2820 ?    Sl     0:01 /usr/libexec/evolution-data-server-1.10 --

and many more...

Adding the 「x」 option (note that there is no leading dash) tells ps to show all of our processes regardless of what terminal (if any) they are controlled by. The presence of a 「?」 in the TTY column indicates no controlling terminal. Using this option, we see a list of every process that we own.

加上 「x」 選項(注意沒有開頭的 「-「 字符),告訴 ps 命令,展現全部進程,無論它們由什麼 終端(若是有的話)控制。在 TTY 一欄中出現的 「?」 ,表示沒有控制終端。使用這個 「x」 選項,能夠 看到咱們所擁有的每一個進程的信息。

Since the system is running a lot of processes, ps produces a long list. It is often helpful to pipe the output from ps into less for easier viewing. Some option combinations also produce long lines of output, so maximizing the terminal emulator window may be a good idea, too.

由於系統中正運行着許多進程,因此 ps 命令的輸出結果很長。爲了方便查看,將ps的輸出管道 到less中一般頗有幫助。一些選項組合也會產生很長的輸出結果,因此最大化 終端仿真器窗口可能也是一個好主意。

A new column titled STAT has been added to the output. STAT is short for 「state」 and reveals the current status of the process:

輸出結果中,新添加了一欄,標題爲 STAT 。STAT 是 「state」 的簡寫,它揭示了進程當前狀態:

Table 11-1: Process States
State Meaning
R Running. This means that the process is running or ready to run.
S Sleeping. A process is not running; rather, it is waiting for an event, such as a keystroke or network packet.
D Uninterruptible Sleep. Process is waiting for I/O such as a disk drive.
T Stopped. Process has been instructed to stop. More on this later.
Z A defunct or 「zombie」 process. This is a child process that has terminated, but has not been cleaned up by its parent.
< A high priority process. It's possible to grant more importance to a process, giving it more time on the CPU. This property of a process is called niceness. A process with high priority is said to be less nice because it's taking more of the CPU's time, which leaves less for everybody else.
N A low priority process. A process with low priority (a 「nice」 process) will only get processor time after other processes with higher priority have been serviced.
表11-1: 進程狀態
狀態 含義
R 運行中。這意味着,進程正在運行或準備運行。
S 正在睡眠。進程沒有運行,而是,正在等待一個事件, 好比說,一個按鍵或者網絡分組。
D 不可中斷睡眠。進程正在等待 I/O,比方說,一個磁盤驅動器的 I/O。
T 已中止. 已經指示進程中止運行。稍後介紹更多。
Z 一個死進程或「殭屍」進程。這是一個已經終止的子進程,可是它的父進程尚未清空它。 (父進程沒有把子進程從進程表中刪除)
< 一個高優先級進程。這可能會授予一個進程更多重要的資源,給它更多的 CPU 時間。 進程的這種屬性叫作 niceness。具備高優先級的進程聽說是很差的(less nice), 由於它佔用了比較多的 CPU 時間,這樣就給其它進程留下不多時間。
N 低優先級進程。 一個低優先級進程(一個「nice」進程)只有當其它高優先級進程被服務了以後,纔會獲得處理器時間。

The process state may be followed by other characters. These indicate various exotic process characteristics. See the ps man page for more detail.

進程狀態信息以後,可能還跟隨其餘的字符。這表示各類外來進程的特性。詳細信息請看 ps 手冊頁。

Another popular set of options is 「aux」 (without a leading dash). This gives us even more information:

另外一個流行的選項組合是 「aux」(不帶開頭的」-「字符)。這會給咱們更多信息:

[me@linuxbox ~]$ ps aux
USER   PID  %CPU  %MEM     VSZ    RSS  TTY   STAT   START   TIME  COMMAND
root     1   0.0   0.0    2136    644  ?     Ss     Mar05   0:31  init
root     2   0.0   0.0       0      0  ?     S&lt;     Mar05   0:00  [kt]

and many more...

This set of options displays the processes belonging to every user. Using the options without the leading dash invokes the command with 「BSD style」 behavior. The Linux version of ps can emulate the behavior of the ps program found in several different Unix implementations. With these options, we get these additional columns:

這個選項組合,可以顯示屬於每一個用戶的進程信息。使用這個選項,能夠喚醒 「BSD 風格」 的輸出結果。 Linux 版本的 ps 命令,能夠模擬幾個不一樣 Unix 版本中的 ps 程序的行爲。經過這些選項,咱們獲得 這些額外的列。

Table 11-2: BSD Style ps Column Headers
Header Meaning
USER User ID. This is the owner of the process.
%CPU CPU usage in percent
%MEM Memory usage in percent
VSZ Virtual memory size
RSS Resident Set Size. The amount of physical memory (RAM) the process is using in kilobytes.
START Time when the process started. For values over twenty four hours, a date is used.
表11-2: BSD 風格的 ps 命令列標題
標題 含義
USER 用戶 ID. 進程的全部者。
%CPU 以百分比表示的 CPU 使用率
%MEM 以百分比表示的內存使用率
VSZ 虛擬內存大小
RSS 進程佔用的物理內存的大小,以千字節爲單位。
START 進程啓動的時間。若它的值超過24小時,則用天表示。

 

用 top 命令動態查看進程

While the ps command can reveal a lot about what the machine is doing, it provides only a snapshot of the machine’s state at the moment the ps command is executed. To see a more dynamic view of the machine’s activity, we use the top command:

雖然 ps 命令可以展現許多計算機運行狀態的信息,可是它只是提供 ps 命令執行時刻的機器狀態快照。 爲了看到更多動態的信息,咱們使用 top 命令:

[me@linuxbox ~]$ top

The top program displays a continuously updating (by default, every 3 seconds) display of the system processes listed in order of process activity. The name 「top」 comes from the fact that the top program is used to see the 「top」 processes on the system. The top display consists of two parts: a system summary at the top of the display, followed by a table of processes sorted by CPU activity:

top 程序以進程活動順序顯示連續更新的系統進程列表。(默認狀況下,每三秒鐘更新一次),」top」這個名字 來源於 top 程序是用來查看系統中「頂端」進程的。top 顯示結果由兩部分組成: 最上面是系統概要,下面是進程列表,以 CPU 的使用率排序。

top - 14:59:20 up 6:30, 2 users, load average: 0.07, 0.02, 0.00
Tasks: 109 total,   1 running,  106 sleeping,    0 stopped,    2 zombie
Cpu(s): 0.7%us, 1.0%sy, 0.0%ni, 98.3%id, 0.0%wa, 0.0%hi, 0.0%si
Mem:   319496k total,   314860k used,   4636k free,   19392k buff
Swap:  875500k total,   149128k used,   726372k free,  114676k cach

 PID  USER       PR   NI   VIRT   RES   SHR  S %CPU  %MEM   TIME+    COMMAND
6244  me         39   19  31752  3124  2188  S  6.3   1.0   16:24.42 trackerd
....

The system summary contains a lot of good stuff. Here’s a rundown:

其中系統概要包含許多有用信息。下表是對系統概要的說明:

Table 11-3: top Information Fields
Row Field Meaning
1 top Name of the program
  14:59:20 Current time of day.
  up 6:30 This is called uptime. It is the amount of time since the machine was last booted. In this example, the system has been up for six and a half hours.
  2 users There are two users logged in.
  load average: Load average refers to the number of processes that are waiting to run, that is, the number of processes that are in a runnable state and are sharing the CPU. Three values are shown, each for a different period of time. The first is the average for the last 60 seconds, the next the previous 5 minutes, and finally the previous 15 minutes. Values under 1.0 indicate that the machine is not busy.
2 Tasks: This summarizes the number of processes and their various process states.
3 Cpu(s): This row describes the character of the activities that the CPU is performing.
  0.7%us 0.7% of the CPU is being used for user processes. This means processes outside of the kernel itself.
  1.0%sy 1.0% of the CPU is being used for system (kernel) processes.
  0.0%ni 0.0% of the CPU is being used by 「nice」 (low priority) processes.
  98.3%id 98.3% of the CPU is idle.
  0.0%wa 0.0% of the CPU is waiting for I/O.
4 Mem: Shows how physical RAM is being used.
5 Swap: Shows how swap space (virtual memory) is being used.
表11-3: top 命令信息字段
行號 字段 意義
1 top 程序名。
  14:59:20 當前時間。
  up 6:30 這是正常運行時間。它是計算機從上次啓動到如今所運行的時間。 在這個例子裏,系統已經運行了六個半小時。
  2 users 有兩個用戶登陸系統。
  load average: 加載平均值是指,等待運行的進程數目,也就是說,處於能夠運行狀態並共享 CPU 的進程個數。 這裏展現了三個數值,每一個數值對應不一樣的時間段。第一個是最後60秒的平均值, 下一個是前5分鐘的平均值,最後一個是前15分鐘的平均值。若平均值低於1.0,則指示計算機 工做不忙碌。
2 Tasks: 總結了進程數目和這些進程的各類狀態。
3 Cpu(s): 這一行描述了 CPU 正在進行的活動的特性。
  0.7%us 0.7% 的 CPU 被用於用戶進程。這意味着進程在內核以外。
  1.0%sy 1.0%的 CPU 時間被用於系統(內核)進程。
  0.0%ni 0.0%的 CPU 時間被用於"nice"(低優先級)進程。
  98.3%id 98.3%的 CPU 時間是空閒的。
  0.0%wa 0.0%的 CPU 時間來等待 I/O。
4 Mem: 展現物理內存的使用狀況。
5 Swap: 展現交換分區(虛擬內存)的使用狀況。

The top program accepts a number of keyboard commands. The two most interesting are h, which displays the program’s help screen, and q, which quits top.

top 程序接受一系列從鍵盤輸入的命令。兩個最有趣的命令是 h 和 q。h,顯示程序的幫助屏幕,q, 退出 top 程序。

Both major desktop environments provide graphical applications that display information similar to top (in much the same way that Task Manager in Windows works), but I find that top is better than the graphical versions because it is faster and it consumes far fewer system resources. After all, our system monitor program shouldn’t be the source of the system slowdown that we are trying to track.

兩個主要的桌面環境都提供了圖形化應用程序,來顯示與 top 程序類似的信息 (和 Windows 中的任務管理器差異很少),可是我以爲 top 程序要好於圖形化的版本, 由於它運行速度快,而且消費不多的系統資源。畢竟,咱們的系統監測程序不能成爲 咱們試圖追蹤的系統怠工的緣由。

 

把一個進程放置到後臺(執行)

Let’s say we wanted to get the shell prompt back without terminating the xlogo program. We’ll do this by placing the program in the background. Think of the terminal as having a foreground (with stuff visible on the surface like the shell prompt) and a background (with hidden stuff behind the surface.) To launch a program so that it is immediately placed in the background, we follow the command with an- 「&」 character:

假如說咱們想讓 shell 提示符返回,卻不終止 xlogo 程序。咱們能夠把 這個程序放到後臺(background)執行。把終端想象是一個有前臺(包含在表層可見的事物,像 shell 提示符) 和後臺(包含表層之下的隱藏的事物)(的設備)。爲了啓動一個程序並讓它當即在後臺 運行,咱們在程序命令以後,加上」&」字符:

[me@linuxbox ~]$ xlogo &
[1] 28236
[me@linuxbox ~]$

After entering the command, the xlogo window appeared and the shell prompt returned, but some funny numbers were printed too. This message is part of a shell feature called job control. With this message, the shell is telling us that we have started job number 1 (「[1]」) and that it has PID 28236. If we run ps, we can see our process:

執行命令以後,這個 xlogo 窗口出現,而且 shell 提示符返回,同時打印一些有趣的數字。 這條信息是 shell 特性的一部分,叫作任務控制 (job control)。經過這條信息,shell 告訴咱們,已經啓動了 任務號(job number)爲1(「[1]」),PID 爲28236的程序。若是咱們運行 ps 命令,能夠看到咱們的進程:

[me@linuxbox ~]$ ps
  PID TTY         TIME   CMD
10603 pts/1   00:00:00   bash
28236 pts/1   00:00:00   xlogo
28239 pts/1   00:00:00   ps

The shell’s job control facility also gives us a way to list the jobs that are have been launched from our terminal. Using the jobs command, we can see this list:

shell 的任務控制功能給出了一種列出從咱們終端中啓動了的任務的方法。執行 jobs 命令,咱們能夠看到這個輸出列表:

[me@linuxbox ~]$ jobs
[1]+ Running            xlogo &

The results show that we have one job, numbered 「1」, that it is running, and that the command was xlogo &.

結果顯示咱們有一個任務,編號爲「1」,它正在運行,而且這個任務的命令是 xlogo &。

進程返回到前臺

A process in the background is immune from keyboard input, including any attempt interrupt it with a Ctrl-c. To return a process to the foreground, use the fg command, this way:

一個在後臺運行的進程對一切來自鍵盤的輸入都免疫,也不能用 Ctrl-c 來中斷它。 爲了讓一個進程返回前臺 (foreground),這樣使用 fg 命令:

[me@linuxbox ~]$ jobs
[1]+ Running        xlogo &
[me@linuxbox ~]$ fg %1
xlogo

The command fg followed by a percent sign and the job number (called a jobspec) does the trick. If we only have one background job, the jobspec is optional. To terminate xlogo, type Ctrl-c.

fg 命令以後,跟隨着一個百分號和任務序號(叫作 jobspec,如此處的%1)就能夠了。若是咱們只有一個後臺任務,那麼 jobspec(job specification) 是無關緊要的。輸入 Ctrl-c 來終止 xlogo 程序。

中止一個進程

Sometimes we’ll want to stop a process without terminating it. This is often done to allow a foreground process to be moved to the background. To stop a foreground process, type Ctrl-z. Let’s try it. At the command prompt, type xlogo, the Enter key, then Ctrl-z:

有時候,咱們想要中止一個進程,而不是終止它。咱們這麼作一般是爲了容許前臺進程被移動到後臺。 輸入 Ctrl-z,能夠中止一個前臺進程。讓咱們試一下。在命令提示符下,執行 xlogo 命令, 而後輸入 Ctrl-z:

[me@linuxbox ~]$ xlogo
[1]+ Stopped                 xlogo
[me@linuxbox ~]$

After stopping xlogo, we can verify that the program has stopped by attempting to resize the xlogo window. We will see that it appears quite dead. We can either restore the program to the foreground, using the fg command, or move the program to the background with the bg command:

中止 xlogo 程序以後,經過調整 xlogo 的窗口大小,咱們能夠證明這個程序已經中止了。 它看起來像死掉了同樣。使用 fg 命令,能夠恢復程序到前臺運行,或者用 bg 命令把程序移到後臺。

[me@linuxbox ~]$ bg %1
[1]+ xlogo &
[me@linuxbox ~]$

As with the fg command, the jobspec is optional if there is only one job.

和 fg 命令同樣,若是隻有一個任務的話,jobspec 參數是可選的。

Moving a process from the foreground to the background is handy if we launch a graphical program from the command, but forget to place it in the background by appending the trailing 「&」.

若是咱們從命令行啓動一個圖形程序,可是忘了在命令後加字符 「&」, 將一個進程從前臺移動到後臺也是很方便的。

Why would you want to launch a graphical program from the command line? There are two reasons. First, the program you wish to run might not be listed on the window manager’s menus (such as xlogo). Secondly, by launching a program from the command line, you might be able to see error messages that would otherwise be invisible if the program were launched graphically. Sometimes, a program will fail to start up when launched from the graphical menu. By launching it from the command line instead, we may see an error message that will reveal the problem. Also, some graphical programs have many interesting and useful command line options.

爲何要從命令行啓動一個圖形界面程序呢?有兩個緣由。第一個,你想要啓動的程序,可能 沒有在窗口管理器的菜單中列出來(比方說 xlogo)。第二個,從命令行啓動一個程序, 你可以看到一些錯誤信息,若是從圖形界面中運行程序的話,這些信息是不可見的。有時候, 一個程序不能從圖形界面菜單中啓動。經過從命令行中啓動它,咱們可能會看到 能揭示問題的錯誤信息。一些圖形界面程序還有許多有意思而且有用的命令行選項。

 

檢查環境變量

We can use either the set builtin in bash or the printenv program to see what is stored in the environment. The set command will show both the shell and environment variables, while printenv will only display the latter. Since the list of environment contents will be fairly long, it is best to pipe the output of either command into less:

咱們能夠用 bash 的內建命令 set,或者是 printenv 程序來查看環境變量。set 命令能夠 顯示 shell 或環境變量,而 printenv 只是顯示環境變量。由於環境變量列表比較長,最好 把每一個命令的輸出經過管道傳遞給 less 來閱讀:

[me@linuxbox ~]$ printenv | less

Doing so, we should get something that looks like this:

執行以上命令以後,咱們應該能獲得相似如下內容:

KDE_MULTIHEAD=false
SSH_AGENT_PID=6666
HOSTNAME=linuxbox
GPG_AGENT_INFO=/tmp/gpg-PdOt7g/S.gpg-agent:6689:1
SHELL=/bin/bash
TERM=xterm
XDG_MENU_PREFIX=kde-
HISTSIZE=1000
XDG_SESSION_COOKIE=6d7b05c65846c3eaf3101b0046bd2b00-1208521990.996705
-1177056199
GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/me/.gtkrc-2.0:/home/me/.kde/sh
are/config/gtkrc-2.0
GTK_RC_FILES=/etc/gtk/gtkrc:/home/me/.gtkrc:/home/me/.kde/share/confi
g/gtkrc
GS_LIB=/home/me/.fonts
WINDOWID=29360136
QTDIR=/usr/lib/qt-3.3
QTINC=/usr/lib/qt-3.3/include
KDE_FULL_SESSION=true
USER=me
LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01
:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:\*.cmd=00;32:\*.exe:

What we see is a list of environment variables and their values. For example, we see a variable called USER, which contains the value 「me」. The printenv command can also list the value of a specific variable:

咱們所看到的是環境變量及其數值的列表。例如,咱們看到一個叫作 USER 的變量,這個變量值是 「me」。printenv 命令也可以列出特定變量的數值:

[me@linuxbox ~]$ printenv USER
me

The set command, when used without options or arguments, will display both the shell and environment variables, as well as any defined shell functions. Unlike printenv, its output is courteously sorted in alphabetical order:

當使用沒有帶選項和參數的 set 命令時,shell 變量,環境變量,和定義的 shell 函數 都會被顯示。不一樣於 printenv 命令,set 命令的輸出很友好地按照首字母順序排列:

[me@linuxbox ~]$ set | less

It is also possible to view the contents of a variable using the echo command, like this:

也能夠經過 echo 命令來查看一個變量的內容,像這樣:

[me@linuxbox ~]$ echo $HOME
/home/me

One element of the environment that neither set nor printenv displays is aliases. To see them, enter the alias command without arguments:

別名沒法經過使用 set 或 printenv 來查看。 用不帶參數的 alias 來查看別名:




[me@linuxbox ~]$ alias alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty' alias vi='vim' alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

一些有趣的環境變量

The environment contains quite a few variables, and though your environment may differ from the one presented here, you will likely see the following variables in your environment:

shell 環境中包含至關多的變量。雖然你的 shell 環境可能與這裏的不一樣,你可能會看到 如下的環境變量:

Table 12-1: Environment Variables
Variable Contents
DISPLAY The name of your display if you are running a graphical environment. Usually this is ":0", meaning the first display generated by the X server.
EDITOR The name of the program to be used for text editing.
SHELL The name of your shell program.
HOME The pathname of your home directory.
LANG Defines the character set and collation order of your language.
OLD_PWD The previous working directory.
PAGER The name of the program to be used for paging output. This is often set to /usr/bin/less.
PATH A colon-separated list of directories that are searched when you enter the name of a executable program.
PS1 Prompt String 1. This defines the contents of your shell prompt. As we will later see, this can be extensively customized.
PWD The current working directory.
TERM The name of your terminal type. Unix-like systems support many terminal protocols; this variable sets the protocol to be used with your terminal emulator.
TZ Specifies your timezone. Most Unix-like systems maintain the computer's internal clock in Coordinated Universal Time (UTC) and then displays the local time by applying an offset specified by this variable.
USER Your user name.
表12-1: 環境變量
變量 內容
DISPLAY 若是你正在運行圖形界面環境,那麼這個變量就是你顯示器的名字。一般,它是 ":0", 意思是由 X 產生的第一個顯示器。
EDITOR 文本編輯器的名字。
SHELL shell 程序的名字。
HOME 用戶家目錄。
LANG 定義了字符集以及語言編碼方式。
OLD_PWD 先前的工做目錄。
PAGER 頁輸出程序的名字。這常常設置爲/usr/bin/less。
PATH 由冒號分開的目錄列表,當你輸入可執行程序名後,會搜索這個目錄列表。
PS1 Prompt String 1. 這個定義了你的 shell 提示符的內容。隨後咱們能夠看到,這個變量 內容能夠全面地定製。
PWD 當前工做目錄。
TERM 終端類型名。類 Unix 的系統支持許多終端協議;這個變量設置你的終端仿真器所用的協議。
TZ 指定你所在的時區。大多數類 Unix 的系統按照協調時間時 (UTC) 來維護計算機內部的時鐘 ,而後應用一個由這個變量指定的誤差來顯示本地時間。
USER 你的用戶名

Don’t worry if some of these values are missing. They vary by distribution.

若是缺失了一些變量,不要擔憂,這些變量會因發行版本的不一樣而不一樣。

 

如何創建 shell 環境?

When we log on to the system, the bash program starts, and reads a series of configuration scripts called startup files, which define the default environment shared by all users. This is followed by more startup files in our home directory that define our personal environment. The exact sequence depends on the type of shell session being started. There are two kinds: a login shell session and a non-login shell session.

當咱們登陸系統後, bash 程序啓動,而且會讀取一系列稱爲啓動文件的配置腳本, 這些文件定義了默認的可供全部用戶共享的 shell 環境。而後是讀取更多位於咱們本身家目錄中 的啓動文件,這些啓動文件定義了用戶我的的 shell 環境。確切的啓動順序依賴於要運行的 shell 會話 類型。有兩種 shell 會話類型:一個是登陸 shell 會話,另外一個是非登陸 shell 會話。

A login shell session is one in which we are prompted for our user name and password; when we start a virtual console session, for example. A non-login shell session typically occurs when we launch a terminal session in the GUI.

登陸 shell 會話會在其中提示用戶輸入用戶名和密碼;例如,咱們啓動一個虛擬控制檯會話。 非登陸 shell 會話一般當咱們在 GUI 下啓動終端會話時出現。

Login shells read one or more startup files as shown in Table 12-2:

登陸 shell 會讀取一個或多個啓動文件,正如表12-2所示:

Table 12-2: Startup Files For Login Shell Sessions
File Contents
/etc/profile A global configuration script that applies to all users.
~/.bash_profile A user's personal startup file. Can be used to extend or override settings in the global configuration script.
~/.bash_login If ~/.bash_profile is not found, bash attempts to read this script.
~/.profile If neither ~/.bash_profile nor ~/.bash_login is found, bash attempts to read this file. This is the default in Debian-based distributions, such as Ubuntu.
表12-2: 登陸 shell 會話的啓動文件
文件 內容
/etc/profile 應用於全部用戶的全局配置腳本。
~/.bash_profile 用戶我的的啓動文件。能夠用來擴展或重寫全局配置腳本中的設置。
~/.bash_login 若是文件 ~/.bash_profile 沒有找到,bash 會嘗試讀取這個腳本。
~/.profile 若是文件 ~/.bash_profile 或文件 ~/.bash_login 都沒有找到,bash 會試圖讀取這個文件。 這是基於 Debian 發行版的默認設置,比方說 Ubuntu。

Non-login shell sessions read the following startup files:

非登陸 shell 會話會讀取如下啓動文件:

Table 12-3: Startup Files For Non-Login Shell Sessions
File Contents
/etc/bash.bashrc A global configuration script that applies to all users.
~/.bashrc A user's personal startup file. Can be used to extend or override settings in the global configuration script.
表12-3: 非登陸 shell 會話的啓動文件
文件 內容
/etc/bash.bashrc 應用於全部用戶的全局配置文件。
~/.bashrc 用戶我的的啓動文件。能夠用來擴展或重寫全局配置腳本中的設置。

In addition to reading the startup files above, non-login shells also inherit the environment from their parent process, usually a login shell.

除了讀取以上啓動文件以外,非登陸 shell 會話也會繼承它們父進程的環境設置,一般是一個登陸 shell。

Take a look at your system and see which of these startup files you have. Remember— since most of the filenames listed above start with a period (meaning that they are hidden), you will need to use the 「-a」 option when using ls.

瀏覽一下你的系統,看一看系統中有哪些啓動文件。記住-由於上面列出的大多數文件名都以圓點開頭 (意味着它們是隱藏文件),你須要使用帶」-a」選項的 ls 命令。

The ~/.bashrc file is probably the most important startup file from the ordinary user’s point of view, since it is almost always read. Non-login shells read it by default and most startup files for login shells are written in such a way as to read the ~/.bashrc file as well.

在普通用戶看來,文件 ~/.bashrc 多是最重要的啓動文件,由於它幾乎老是被讀取。非登陸 shell 默認 會讀取它,而且大多數登陸 shell 的啓動文件會以能讀取 ~/.bashrc 文件的方式來書寫。

一個啓動文件的內容

If we take a look inside a typical .bash_profile (taken from a CentOS 4 system), it looks something like this:

若是咱們看一下典型的 .bash_profile 文件(來自於 CentOS 4 系統),它看起來像這樣:

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH

Lines that begin with a 「#」 are comments and are not read by the shell. These are there for human readability. The first interesting thing occurs on the fourth line, with the following code:

以」#」開頭的行是註釋,shell 不會讀取它們。它們在那裏是爲了方便人們閱讀。第一件有趣的事情 發生在第四行,伴隨着如下代碼:

if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

This is called an if compound command, which we will cover fully when we get to shell scripting in Part 5, but for now we will translate:

這叫作一個 if 複合命令,咱們將會在第五部分詳細地介紹它,如今咱們對它翻譯一下:

If the file ~/.bashrc exists, then
read the ~/.bashrc file.

We can see that this bit of code is how a login shell gets the contents of .bashrc. The next thing in our startup file has to do with the PATH variable.

咱們能夠看到這一小段代碼就是一個登陸 shell 獲得 .bashrc 文件內容的方式。在咱們啓動文件中, 下一件有趣的事與 PATH 變量有關係。

Ever wonder how the shell knows where to find commands when we enter them on the command line? For example, when we enter ls, the shell does not search the entire computer to find /bin/ls (the full pathname of the ls command), rather, it searches a list of directories that are contained in the PATH variable.

是否曾經對 shell 怎樣知道在哪裏找到咱們在命令行中輸入的命令感到迷惑?例如,當咱們輸入 ls 後, shell 不會查找整個計算機系統來找到 /bin/ls(ls 命令的全路徑名),相反,它查找一個目錄列表, 這些目錄包含在 PATH 變量中。

The PATH variable is often (but not always, depending on the distribution) set by the /etc/profile startup file and with this code:

PATH 變量常常(但不老是,依賴於發行版)在 /etc/profile 啓動文件中設置,經過這些代碼:

PATH=$PATH:$HOME/bin

PATH is modified to add the directory $HOME/bin to the end of the list. This is an example of parameter expansion, which we touched on in Chapter 8. To demonstrate how this works, try the following:

修改 PATH 變量,添加目錄 $HOME/bin 到目錄列表的末尾。這是一個參數展開的實例, 參數展開咱們在第八章中提到過。爲了說明這是怎樣工做的,試試下面的例子:

[me@linuxbox ~]$ foo="This is some"
[me@linuxbox ~]$ echo $foo
This is some
[me@linuxbox ~]$ foo="$foo text."
[me@linuxbox ~]$ echo $foo
This is some text.

Using this technique, we can append text to the end of a variable’s contents. By adding the string $HOME/bin to the end of the PATH variable’s contents, the directory $HOME/bin is added to the list of directories searched when a command is entered. This means that when we want to create a directory within our home directory for storing our own private programs, the shell is ready to accommodate us. All we have to do is call it bin, and we’re ready to go.

使用這種技巧,咱們能夠把文本附加到一個變量值的末尾。經過添加字符串 $HOME/bin 到 PATH 變量值 的末尾,則目錄 $HOME/bin 就添加到了命令搜索目錄列表中。這意味着當咱們想要在本身的家目錄下, 建立一個目錄來存儲咱們本身的私人程序時,shell 已經給咱們準備好了。咱們所要作的事就是 把建立的目錄叫作 bin,趕快行動吧。

Note: Many distributions provide this PATH setting by default. Some Debian based distributions, such as Ubuntu, test for the existence of the ~/bin directory at login, and dynamically add it to the PATH variable if the directory is found.

注意:不少發行版默認地提供了這個 PATH 設置。一些基於 Debian 的發行版,例如 Ubuntu,在登陸 的時候,會檢測目錄 ~/bin 是否存在,若找到目錄則把它動態地加到 PATH 變量中。

Lastly, we have:

最後,有下面一行代碼:

export PATH

The export command tells the shell to make the contents of PATH available to child processes of this shell.

這個 export 命令告訴 shell 讓這個 shell 的子進程可使用 PATH 變量的內容。

 

激活咱們的修改

The changes we have made to our .bashrc will not take affect until we close our terminal session and start a new one, since the .bashrc file is only read at the beginning of a session. However, we can force bash to re-read the modified .bashrc file with the following command:

咱們對於文件 .bashrc 的修改不會生效,直到咱們關閉終端會話,再從新啓動一個新的會話, 由於 .bashrc 文件只是在剛開始啓動終端會話時讀取。然而,咱們能夠強迫 bash 從新讀取修改過的 .bashrc 文件,使用下面的命令:

[me@linuxbox ~]$ source .bashrc

After doing this, we should be able to see the effect of our changes. Try out one of the new aliases:

運行上面命令以後,咱們就應該可以看到所作修改的效果了。試試其中一個新的別名:





[me@linuxbox ~]$ ll

編寫第一個 Shell 腳本

什麼是 Shell 腳本?

In the simplest terms, a shell script is a file containing a series of commands. The shell reads this file and carries out the commands as though they have been entered directly on the command line.

最簡單的解釋,一個 shell 腳本就是一個包含一系列命令的文件。shell 讀取這個文件,而後執行 文件中的全部命令,就好像這些命令已經直接被輸入到了命令行中同樣。

The shell is somewhat unique, in that it is both a powerful command line interface to the system and a scripting language interpreter. As we will see, most of the things that can be done on the command line can be done in scripts, and most of the things that can be done in scripts can be done on the command line.

Shell 有些獨特,由於它不只是一個功能強大的命令行接口,也是一個腳本語言解釋器。咱們將會看到, 大多數可以在命令行中完成的任務也可以用腳原本實現,一樣地,大多數能用腳本實現的操做也可以 在命令行中完成。

We have covered many shell features, but we have focused on those features most often used directly on the command line. The shell also provides a set of features usually (but not always) used when writing programs.

雖然咱們已經介紹了許多 shell 功能,但只是集中於那些常常直接在命令行中使用的功能。 Shell 也提供了一些一般(但不老是)在編寫程序時才使用的功能。

怎樣編寫一個 Shell 腳本

To successfully create and run a shell script, we need to do three things:

爲了成功地建立和運行一個 shell 腳本,咱們須要作三件事情:

  1. Write a script. Shell scripts are ordinary text files. So we need a text editor to write them. The best text editors will provide syntax highlighting, allowing us to see a color-coded view of the elements of the script. Syntax highlighting will help us spot certain kinds of common errors. vim, gedit, kate, and many other editors are good candidates for writing scripts.

  2. Make the script executable. The system is rather fussy about not letting any old text file be treated as a program, and for good reason! We need to set the script file’s permissions to allow execution.

  3. Put the script somewhere the shell can find it. The shell automatically searches certain directories for executable files when no explicit pathname is specified. For maximum convenience, we will place our scripts in these directories.

  1. 編寫一個腳本。 Shell 腳本就是普通的文本文件。因此咱們須要一個文本編輯器來書寫它們。最好的文本 編輯器都會支持語法高亮,這樣咱們就可以看到一個腳本關鍵字的彩色編碼視圖。語法高亮會幫助咱們查看某種常見 錯誤。爲了編寫腳本文件,vim,gedit,kate,和許多其它編輯器都是不錯的候選者。

  2. 使腳本文件可執行。 系統會至關挑剔不容許任何舊的文本文件被看做是一個程序,而且有充分的理由! 因此咱們須要設置腳本文件的權限來容許其可執行。

  3. 把腳本放置到 shell 可以找到的地方。 當沒有指定可執行文件明確的路徑名時,shell 會自動地搜索某些目錄, 來查找此可執行文件。爲了最大程度的方便,咱們會把腳本放到這些目錄當中。

腳本文件格式

In keeping with programming tradition, we’ll create a 「hello world」 program to demonstrate an extremely simple script. So let’s fire up our text editors and enter the following script:

爲了保持編程傳統,咱們將建立一個 「hello world」 程序來講明一個極端簡單的腳本。因此讓咱們啓動 咱們的文本編輯器,而後輸入如下腳本:

#!/bin/bash # This is our first script. echo 'Hello World!' 

The last line of our script is pretty familiar, just an echo command with a string argument. The second line is also familiar. It looks like a comment that we have seen used in many of the configuration files we have examined and edited. One thing about comments in shell scripts is that they may also appear at the end of lines, like so:

對於腳本中的最後一行,咱們應該是至關的熟悉,僅僅是一個帶有一個字符串參數的 echo 命令。 對於第二行也很熟悉。它看起來像一個註釋,咱們已經在許多咱們檢查和編輯過的配置文件中 看到過。關於 shell 腳本中的註釋,它們也能夠出如今文本行的末尾,像這樣:

echo 'Hello World!' # This is a comment too

Everything from the # symbol onward on the line is ignored.

文本行中,# 符號以後的全部字符都會被忽略。

Like many things, this works on the command line, too:

相似於許多命令,這也在命令行中起做用:

[me@linuxbox ~]$ echo 'Hello World!' # This is a comment too
Hello World!

Though comments are of little use on the command line, they will work.

雖然不多在命令行中使用註釋,但它們也能起做用。

The first line of our script is a little mysterious. It looks like it should be a comment, since it starts with #, but it looks too purposeful to be just that. The #! character sequence is, in fact, a special construct called a shebang. The shebang is used to tell the system the name of the interpreter that should be used to execute the script that follows. Every shell script should include this as its first line.

咱們腳本中的第一行文本有點兒神祕。它看起來它應該是一條註釋,由於它起始於一個#符號,可是 它看起來太有意義,以致於不只僅是註釋。事實上,這個#!字符序列是一種特殊的結構叫作 shebang。 這個 shebang 被用來告訴操做系統將執行此腳本所用的解釋器的名字。每一個 shell 腳本都應該把這一文本行 做爲它的第一行。

Let’s save our script file as hello_world.

讓咱們把此腳本文件保存爲 hello_world。

可執行權限

The next thing we have to do is make our script executable. This is easily done using chmod:

下一步咱們要作的事情是讓咱們的腳本可執行。使用 chmod 命令,這很容易作到:

[me@linuxbox ~]$ ls -l hello_world
-rw-r--r-- 1  me    me      63  2009-03-07 10:10 hello_world
[me@linuxbox ~]$ chmod 755 hello_world
[me@linuxbox ~]$ ls -l hello_world
-rwxr-xr-x 1  me    me      63  2009-03-07 10:10 hello_world

There are two common permission settings for scripts; 755 for scripts that everyone can execute, and 700 for scripts that only the owner can execute. Note that scripts must be readable in order to be executed.

對於腳本文件,有兩個常見的權限設置;權限爲755的腳本,則每一個人都能執行,和權限爲700的 腳本,只有文件全部者可以執行。注意爲了可以執行腳本,腳本必須是可讀的。

 

Configuring vim For Script Writing

爲書寫腳本配置 vim

The vim text editor has many, many configuration settings. There are several common options that can facilitate script writing:

這個 vim 文本編輯器有許多許多的配置設置。有幾個常見的選項可以有助於腳本書寫:

:syntax on

turns on syntax highlighting. With this setting, different elements of shell syntax will be displayed in different colors when viewing a script. This is helpful for identifying certain kinds of programming errors. It looks cool, too. Note that for this feature to work, you must have a complete version of vim installed, and the file you are editing must have a shebang indicating the file is a shell script. If you have difficulty with the command above, try :set syntax=sh instead.

打開語法高亮。經過這個設置,當查看腳本的時候,不一樣的 shell 語法元素會以不一樣的顏色 顯示。這對於識別某些編程錯誤頗有幫助。而且它看起來也很酷。注意爲了這個功能起做用,你 必須安裝了一個完整的 vim 版本,而且你編輯的文件必須有一個 shebang,來講明這個文件是 一個 shell 腳本。若是對於上面的命令,你遇到了困難,試試 :set syntax=sh。

:set hlsearch

turns on the option to highlight search results. Say we search for the word 「echo.」 With this option on, each instance of the word will be highlighted.

打開這個選項是爲了高亮查找結果。好比說咱們查找單詞「echo」。經過設置這個選項,這個 單詞的每一個實例會高亮顯示。

:set tabstop=4

sets the number of columns occupied by a tab character. The default is eight columns. Setting the value to four (which is a common practice) allows long lines to fit more easily on the screen.

設置一個 tab 字符所佔據的列數。默認是8列。把這個值設置爲4(一種常見作法), 從而讓長文本行更容易適應屏幕。

:set autoindent

turns on the 「auto indent」 feature. This causes vim to indent a new line the same amount as the line just typed. This speeds up typing on many kinds of programming constructs. To stop indentation, type Ctrl-d.

打開 「auto indent」 功能。這致使 vim 能對新的文本行縮進與剛輸入的文本行相同的列數。 對於許多編程結構來講,這就加速了輸入。中止縮進,輸入 Ctrl-d。

These changes can be made permanent by adding these commands (without the leading colon characters) to your ~/.vimrc file.

經過把這些命令(沒有開頭的冒號字符)添加到你的 ~/.vimrc 文件中,這些改動會永久生效。

相關文章
相關標籤/搜索