目录
我認爲學習一個計算機系統,就像學習一門新的外語。雖然教程和文檔是有幫助的,但你必須自己練習。爲了幫助你平滑起步,我詳細說明一些基本要點。
DebianGNULinux中最強大的設計來自Unix操作系統,一個多用戶多任務的操作系統。你必須學會利用這些特性以及Unix和GNU/Linux的相似性。
別迴避面向Unix的文檔,不要只是依賴於GNU/Linux文檔,這樣做會剝奪你瞭解許多有用的信息。
![]() |
注意 |
---|---|
如果你在任何類Unix系統中使用過一端時間的命令行工具,你可能已經掌握了這份文檔中的內容。那請把它當做一個實戰檢驗和進修。 |
啓動系統之後,如果你沒有安裝X
窗口系統和顯示管理器(例如gdm3
),那麼你就會看對字符登錄界面。假設你的主機名爲foo
,那麼登錄提示符將如下所示。
foo login:
如果你安裝了一個 GUI 環境,例如 GNOME 或 KDE,那麼你能夠用 Ctrl-Alt-F1進入登錄提示符,同時你可以通過Alt-F7回到GUI環境(更多詳情請參閱下文第 1.1.6 节 “虛擬控制檯”)。
在登錄提示符下,你輸入你的用戶名,例如penguin
,然後按回車鍵,接下來輸入你的密碼並再次按回車鍵。
![]() |
注意 |
---|---|
遵循Unix傳統,Debian系統下的用戶名和密碼是大小寫敏感的。用戶名通常由小寫字母組成。第一個用戶賬號通常在安裝期間進行創建。額外的用戶賬號由root用戶用 adduser(8)創建。 |
系統以保存在 "/etc/motd
" 中的歡迎信息(Message Of The
Day)來開始,同時顯示一個命令提示符。
Debian GNU/Linux jessie/sid foo tty1 foo login: penguin Password: Last login: Mon Sep 23 19:36:44 JST 2013 on tty3 Linux snoopy 3.11-1-amd64 #1 SMP Debian 3.11.6-2 (2013-11-01) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. foo:~$
在這裏,歡迎消息的主要部分能通過編輯 "/etc/motd.tail
" 文件來自定義。第一行是使用
"uname -snrvm
" 輸出的系統信息來生成的。
現在,你就在 shell 下。shell 解析你的命令。
如果你安裝了帶有顯示管理器的X Window
System,例如通過在安裝Debian時選擇“桌面環境”所安裝GNOME的gdm3
,那麼你在啓動系統後將使用圖形登陸界面。輸入你的用戶名和密碼可以登陸到非特權用戶賬號。使用tab可以在用戶名和密碼之間移動,也可以使用鼠標左擊。
要在X窗口下獲得shell提示符,你必須啓動一個x終端模擬器
程序,例如gnome-terminal(1)、rxvt(1)或xterm(1)。在GNOME桌面環境下,你可以點擊“應用程序”→“附件”→“終端”來打開終端。
你還可以看下下面的 第 1.1.6 节 “虛擬控制檯” 章節。
在其它一些桌面系統(如
fluxbox
)下面,可能沒有明顯的開始菜單入口。如果是這種情況,試下右擊桌面屏幕並希望能有彈出菜單。
root 賬戶也被稱作超級用戶或特權用戶。用這個賬戶,你能夠履行下面的系統管理任務。
讀、寫和刪除系統上的任何文件,不顧它們的文件權限
設置系統上任何文件的所有者和權限
設置系統上任何非特權用戶的密碼
免用戶密碼登錄任何用戶
無限權力的 root 賬戶,要求你慎重和負責任的使用。
![]() |
警告 |
---|---|
從來不和其他人共享 root 密碼。 |
![]() |
注意 |
---|---|
一個文件(包括硬件設備,如CD-ROM等,這些對Debian系統來說都只是一個文件)的權限可能會導致非root用戶無法使用或訪問它 。雖然在這種情況下,使用root帳戶是一個快速的方法,但正確的解決方法應該是對文件權限和用戶組的成員進行合適的設置(參見第 1.2.3 节 “文件系統權限”)。 |
這裏有一些基本的方法可以讓你在輸入root密碼後獲得root的shell提示符。
在字符登陸界面使用root
作爲用戶名登陸。
在GNOME桌面環境下點擊“應用程序”→“附件”→“Root Terminal"。
在任意用戶的shell提示符下輸入“su -l
”。
這不會保存當前用戶的環境設定。
在任意用戶的shell提示符下輸入“su
”。
這會保存當前用戶的一些環境設定。
如果你的桌面菜單沒有適當的權限啓動系統管理工具,你可以在X終端模擬器(例如gnome-terminal(1)、rxvt(1)或xterm(1))中root的shell提示符下啓動它。參見第 1.1.4 节 “root shell 提示符”和第 7.8.5 节 “Running X clients as root”。
![]() |
警告 |
---|---|
永遠不要以根帳號鍵入 |
![]() |
警告 |
---|---|
永遠不要在顯示關鍵信息的X Window下運行不受信任的遠程GUI程序,因爲它可能會監聽你的X屏幕。 |
在默認的Debian系統中,有6個可切換的類VT100字符控制檯,可以直接在Linux主機上啓動shell。除非你處於GUI環境下,否則你可以同時按下左Alt鍵
和F1
—F6
之一的鍵在虛擬控制檯間切換。每一個字符控制檯都允許獨立登陸賬戶並提供多用戶環境。這個多用戶環境是偉大的Unix的特性,很容易上癮。
如果你處於X Window
System中,你可以通過Ctrl-Alt-F1
鍵前往字符控制檯1,也就是同時按下左Ctrl鍵
、左Alt鍵
和F1鍵
。你可以按下Alt-F7
回到X
Window System,它一般運行在虛擬控制檯7。
你也可以使用命令行切換到另一個虛擬控制檯,例如切換到控制檯1。
# chvt 1
在命令行輸入Ctrl-D
,即同時按下左側-Ctrl-鍵
和d-鍵
,即可關閉
shell 活動。如果你正處於字符控制檯,你將會返回到登錄提示行。儘管這些控制字符 “control D" 使用了大寫字母,你並不需要按住
Shift-鍵。Ctrl-D
也可以簡寫爲 ^D
。或者,你也可以鍵入
”exit" 退出命令行。
如果你位於x終端模擬器(1)中,你可以使用這個關閉x終端模擬器
窗口。
就像任何其他的現代操作系統一樣,Debian會通過內存中的緩存數據進行文件操作以提高性能,因此在電源被安全地關閉前需要適當的關機過程,通過將內存中的數據強制寫入硬盤來維持文件的完整性。如果軟件的電源控制可用,那麼關機過程中會自動關閉系統電源。(否則,你可能需要在關機過程之後按電源鍵幾秒鐘。)
在普通多用戶模式模式下,可以使用命令行關閉系統。
# shutdown -h now
在單用戶模式下,可以使用命令行關閉系統。
# poweroff -i -f
另外,如果在“/etc/inittab
”中含有“ca:12345:ctrlaltdel:/sbin/shutdown
-t1 -a -h
now
”,那麼你可以按下Ctrl-Alt-Delete
(同時按下左Ctrl鍵
、左Alt鍵
和Delete
)來關機。參見inittab(5)獲取更多細節。
當做了一些滑稽的事(例如“cat<二進制文件>
”)後,屏幕會發狂,你可以在命令行輸入“reset
”。你可能無法在屏幕上看到你輸入的命令。你也可以輸入“clear
”來清屏。
儘管連無需任何桌面環境的 Debian 系統最小安裝都提供了基本的 Unix 功能,但對新手而言,使用
apt-get(8)
安裝一些基於字符終端的命令行和 curses 軟件包(例如 mc
和
vim
)依舊是一個不錯的主意。
# apt-get update ... # apt-get install mc vim sudo ...
如果你已經安裝了這些軟件包,那麼不會有新的軟件包被安裝。
表 1.1. 有趣的文本模式程序包列表
軟件包 | 流行度 | 大小 | 說明 |
---|---|---|---|
mc
|
V:72, I:238 | 1431 | 文本模式的全屏文件管理器 |
sudo
|
V:346, I:702 | 2933 | 給普通用戶授予部分 root 權限的程序 |
vim
|
V:127, I:390 | 2366 | Unix 文本編輯器 Vi 的改進版,一個程序員的文本編輯器(標準版) |
vim-tiny
|
V:73, I:968 | 1063 | Unix 文本編輯器 Vi 的改進版,一個程序員的文本編輯器(精簡版) |
emacs25
|
V:0, I:0 | 19423 | GNU 項目的 Emacs,基於 Lisp 的擴展文本編輯器 |
w3m
|
V:269, I:840 | 2289 | 文本模式的萬維網瀏覽器 |
gpm
|
V:14, I:22 | 457 | 文本控制檯 Unix 式樣的粘貼拷貝(守護) |
閱讀一些信息文檔,也是一個好的主意。
表 1.2. 軟件包信息文檔列表
軟件包 | 流行度 | 大小 | 說明 |
---|---|---|---|
doc-debian
|
I:858 | 166 | Debian 項目文檔,(Debian 常見問題)和其它文檔 |
debian-policy
|
I:111 | 3744 | Debian 策略手冊和相關文檔 |
developers-reference
|
I:7 | 1299 | Debian 開發者指導方針和信息 |
maint-guide
|
I:5 | 1011 | Debian 新維護者手冊 |
debian-history
|
I:1 | 4895 | Debian 項目歷史 |
debian-faq
|
I:843 | 1277 | Debian 常見問題 |
你可以用下面的命令安裝這些包。
# apt-get install package_name
如果你不想用你自己的主用戶賬戶來進行下面的練習操作,你可以使用下面的方式創建一個練習用戶賬戶,比如說,創建一個用戶名爲
fish
的賬號。
# adduser fish
回答所有問題。
這將創建一個名爲 fish
的新賬號。在你練習完成後,你可以使用下面的命令刪除這個用戶賬號和它的用戶主目錄。
# deluser --remove-home fish
對於典型的單用戶工作站,例如運行在筆記本電腦上的桌面Debian系統,通常簡單地配置sudo(8)來使爲非特權用戶(例如用戶penguin
)只需輸入用戶密碼而非root密碼就能獲得管理員權限。
# echo "penguin ALL=(ALL) ALL" >> /etc/sudoers
另外,可以使用下列命令使非特權用戶(例如用戶penguin
)無需密碼就獲得管理員權限。
# echo "penguin ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
這些技巧只對你管理的單用戶工作站中那個唯一的用戶有用。
![]() |
警告 |
---|---|
在多用戶工作站中不要建立這樣的普通用戶賬戶,因爲它會導致非常嚴重的系統安全問題。 |
![]() |
小心 |
---|---|
在上述例子中,用戶 |
![]() |
小心 |
---|---|
在這種情況下,管理員權限被賦予那些有權對工作站進行系統管理任務的人。永遠不要讓你的公司行政管理部門或你的老闆進行管理(例如給予他們權限),除非他們獲得了授權並有這樣的能力。 |
![]() |
注意 |
---|---|
爲了對受限的設備和文件提供訪問權限,你應該考慮使用組來提供受限訪問,而不是通過sudo(8)來使用root權限。 |
![]() |
注意 |
---|---|
隨着越來越細緻周密的配置,sudo(8)可以授予一個共享系統上的其它用戶有限的管理權限而不共享root密碼。這可以幫助對有多個管理員的主機進行責任追究,你可以瞭解到是誰做什麼。另一方面,你可能不想任何人有這樣的權限。 |
現在你已經準備好玩 Debian 系統了,只要你使用非特權用戶賬號就不會有風險。
這是因爲 Debian 系統(即使是默認安裝)會設置適當的文件權限來防止非特權用戶對系統造成破壞。當然,可能仍然有一些漏洞可以利用,但關心這些問題的人不應該閱讀這一節,而應該去閱讀 Debian 安全手冊。
我們使用下面的方式,把 Debian 系統當作一個 類 Unix 系統來學習。
第 1.2 节 “類 Unix 文件系統” (基本概念)
第 1.5 节 “簡單 shell 命令” (shell 機制)
第 1.6 节 “類 Unix 的文本處理” (文本處理方式)
在GNU/Linux和其他類Unix操作系統中,文件被組織到目錄中。所有的文件和目錄排放在以“/
”爲根的巨大的樹裏。叫它樹是因爲如果你畫出文件系統,它看起來就像一棵樹,但是它是顛倒過來的。
這些文件和目錄可以分散在多個設備中。mount(8)用於把某個設備上找到的文件系統附着到巨大的文件樹上。相反的,umount(8)把它再次分離。在當前的Linux內核裏mount(8)帶某些參數,可以把文件樹的一部分綁定到另外的地方,或者可以把文件系統掛載爲共享的、私有的、從設備、或不可綁定的。對每個文件系統支持的掛載選項可以在/share/doc/linux-doc-*/Documentation/filesystems/
找到。
Unix系統上叫做目錄,某些其他系統上叫做文件夾。請同樣留意,在任何Unix系統上,沒有的驅動器的概念,例如“A:
”。這只有一個文件系統,並且所有東西都包含在內。這相對於Windows來說是一個巨大的優點。
下面是一些 Unix 文件基礎。
文件名是 區分大小寫 的。也就是說,
"MYFILE
" 和 "MyFile
" 是不同的文件。
根目錄意味着文件系統的根,簡單的稱爲“/
”,不要把它跟root用戶的家目錄“/root
”混淆了。
每個目錄都有一個名字,它可以包含任意字母或除了/
”以外的符號。根目錄是個特例。它的名字是“/
”(稱作“斜線”或“根目錄”),並且它不能被重命名。
每個文件或目錄都被指定一個全限定文件名,絕對文件名,或路徑,按順序給出必須經過的目錄從而到達相應目錄。這三個術語是同義的。
所有的全限定文件名以“/
”目錄開始,並且在每個目錄或文件名之間有一個“/
”。第一個“/
”是最頂層目錄,其他的“/
”用於分隔跟着的子目錄。直到到達最後的入口,即實際文件的名稱。這些話可能會令人困惑。用下面這個全限定文件名作爲例子:“/usr/share/keytables/us.map.gz
”。不過,人們也把它的基名“us.map.gz
”單獨作爲文件名。
根目錄有很多分支,例如“/etc/
”和“/usr/
”。這些子目錄依次分出更多的子目錄,例如“/etc/init.d/
”和“/usr/local/
”。這整體叫做“目錄樹”。你可以把一個絕對文件名想象成從“/
”這棵樹的基到某個分支(一個文件)的結尾的一條路徑。你也聽到人們談論目錄樹,就好像它是一個包含所有直系後代的“家庭”樹的一個圖,這個圖叫做根目錄(“/
”):因此子目錄有父目錄,並且一條路徑顯示了一個文件完整的祖先。也有相對路徑從其他地方開始,而不是從根目錄。
你應該還記得目錄“../
”指向父目錄。這個術語也適用於其他類似目錄的結構,如分層數據結構。
對於一個物理設備, 是沒有一個特定的目錄路徑名來對應的組成部分. 這不同於RT-11,
CP/M,OpenVMS,MS-DOS,AmigaOS, 以及微軟的Windows,這些系統存在一個路徑包含了一個設備名字,比如"C:\
"。(儘管如此,
路徑條目確實存在引用了物理設備作爲正常的文件系統的一部分. 參考第 1.2.2 节 “文件系統深入解析”。)
![]() |
注意 |
---|---|
雖然你可以在文件名中使用任意的字幕或者符號,
但是在實際情況下這樣做是一個壞主意. 最好避免使用一些在命令行裏面含有特殊意義的字符, 比如空格, 製表符, 換行符, 和其它的特殊字符:
|
![]() |
注意 |
---|---|
這個 "root" 可能既表示 "超級用戶root" 又表示 " 根目錄"(/root) . 應該根據上下文確定它的用法. |
![]() |
注意 |
---|---|
單詞path不僅表示包含全限定文件名, 也可能表示命令搜索的路徑. 通常路徑真實的意思是需要通過上下文來明確. |
關於文件層次的最佳詳細實踐在文件系統層次標準("/usr/share/doc/debian-policy/fhs/fhs-2.3.txt.gz
"
和 hier
(7)).
你應該記住以下的一些標準作爲開始學習的步驟.
Following the Unix tradition, the Debian
GNU/Linux system provides the filesystem
under which physical data on hard disks and other storage devices reside,
and the interaction with the hardware devices such as console screens and
remote serial consoles are represented in an unified manner under
"/dev/
".
每個文件,目錄,命名管道(一種兩個程序間共享數據的方法),或 Debian GNU/Linux 系統上的物理設備都有一個叫做 inode的數據結構,描述了其相關屬性,例如擁有它的用戶(所有者),它屬於的組,最後一次訪問時間,等等。如果你感興趣的話,可以打開
Debian GNU/Linux 系統裏面的 “/usr/include/linux/fs.h
”
看一下關於“inode結構
”的準確定義。這個在文件系統裏面表示所有東西的創意是 Unix 系統的創新,現代
Linux 內核進一步發展了這個創意。現在,甚至在計算機中運行的進程的信息都可以在文件系統裏面找到。
這個對物理實體和內部進程的統一和抽象是非常強大的,因爲這允許我們用同樣的命令對許多完全不同的設備進行同樣的操作。甚至可以通過向鏈接到運行進程的特殊文件寫入數據來改變內核的運行方式。
![]() |
提示 |
---|---|
如果你需要識別文件樹和物理實體之間的對應關係,不帶參數運行mount(8)。 |
擁有這個文件的用戶(u)
這個文件所屬組的其他用戶(g)
所有其餘的用戶(o),同樣稱爲“世界”和“所有人”
對文件來說,每個對應權限允許下列動作。
可讀(r)權限允許所有者檢查文件的內容。
可寫(w)權限允許所有者修改文件內容。
可執行(x)權限允許所有者把文件當做一個命令運行。
對於目錄來說,每個對應權限允許下列動作。
可讀(r)權限允許所有者列出目錄內的內容。
可寫(w)權限允許所有者添加或刪除目錄裏面的文件。
可執行(x)權限允許所有者訪問目錄裏的文件。
在這裏,一個目錄的可執行權限意味着不僅允許讀目錄裏的文件,還允許顯示他們的屬性,例如大小和修改時間。
ls(1)用於顯示文件和目錄的權限信息(更多)。當運行時帶有“-l
”選項,它將按給定順序顯示下列信息。
文件類型(第一個字母)
文件的訪問權限(9個字符,三個字符組成一組按照用戶、組、其他的順序表示)
鏈接到文件的硬鏈接數
文件所有者的用戶名
這個文件所屬的組名
以字符(字節)爲單位的文件大小
文件的日期和時間(mtime)
文件的名字
chown(1)用於
root
賬戶修改文件的所有者。chgrp(1)用於文件的所有者或
root
賬戶修改文件所屬的組。chmod(1)用於文件的所有者或root賬戶修改文件和文件夾的訪問權限。操作一個foo
文件的基本語法如下
。
# chown <newowner> foo # chgrp <newgroup> foo # chmod [ugoa][+-=][rwxXst][,...] foo
例如,你可以按照下面使一個目錄樹被用戶foo
所有,並共享給組bar
。
# cd /some/location/ # chown -R foo:bar . # chmod -R ug+rwX,o=rX .
有三個更加特殊的權限位。
Set_User_ID位(s或S替換用戶的x)
Set_Group_ID位(s或S替換組的x)
粘置位(t或T替代其他用戶的x)
Here the output of "ls -l
" for these bits is capitalized if execution bits hidden by these
outputs are unset.
給一個可執行文件設置Set-User-ID位將允許一個用戶以他自己的ID運行這個可執行文件(例如root)。類似的,給一個可執行文件設置了Set-Group-ID位將允許一個用戶以文件的組ID運行該文件。(例如root組)。由於這些設置可能引起安全風險,使能它們的時候需要格外留意。
在一個目錄上設置“Set-Group-ID”將打開類 BSD 的文件創建計劃,所有在目錄裏面創建的文件將屬於目錄所屬的組。
Setting the sticky bit on a directory
prevents a file in the directory from being removed by a user who is not the
owner of the file. In order to secure contents of a file in world-writable
directories such as "/tmp
" or in group-writable
directories, one must not only reset the write permission for the file but also set the
sticky bit on the directory. Otherwise,
the file can be removed and a new file can be created with the same name by
any user who has write access to the directory.
這裏有少量有趣的文件權限例子。
$ ls -l /etc/passwd /etc/shadow /dev/ppp /usr/sbin/exim4 crw------T 1 root root 108, 0 Oct 16 20:57 /dev/ppp -rw-r--r-- 1 root root 2761 Aug 30 10:38 /etc/passwd -rw-r----- 1 root shadow 1695 Aug 30 10:38 /etc/shadow -rwsr-xr-x 1 root root 973824 Sep 23 20:04 /usr/sbin/exim4 $ ls -ld /tmp /var/tmp /usr/local /var/mail /usr/src drwxrwxrwt 14 root root 20480 Oct 16 21:25 /tmp drwxrwsr-x 10 root staff 4096 Sep 29 22:50 /usr/local drwxr-xr-x 10 root root 4096 Oct 11 00:28 /usr/src drwxrwsr-x 2 root mail 4096 Oct 15 21:40 /var/mail drwxrwxrwt 3 root root 4096 Oct 16 21:20 /var/tmp
There is an alternative numeric mode to describe file permissions with chmod(1). This numeric mode uses 3 to 4 digit wide octal (radix=8) numbers.
表 1.5. chmod(1) 命令文件權限的數字模式
數字 | 說明 |
---|---|
第一個可選數字 | set user ID (=4), set group ID (=2) 和 sticky bit (=1) 之和 |
第二個數字 | read (=4), write (=2), 和 execute (=1) 權限之和, user 用戶 |
第三個數字 | 同上, group |
第四個數字位 | 同上, other |
This sounds complicated but it is actually quite simple. If you look at the
first few (2-10) columns from "ls -l
" command output and
read it as a binary (radix=2) representation of file permissions ("-" being
"0" and "rwx" being "1"), the last 3 digit of the numeric mode value should
make sense as an octal (radix=8) representation of file permissions to you.
嘗試下列例子
$ touch foo bar $ chmod u=rw,go=r foo $ chmod 644 bar $ ls -l foo bar -rw-r--r-- 1 penguin penguin 0 Oct 16 21:39 bar -rw-r--r-- 1 penguin penguin 0 Oct 16 21:35 foo
![]() |
提示 |
---|---|
If you need to access information displayed by " |
What permissions are applied to a newly created file or directory is
restricted by the umask
shell builtin command. See
dash(1),
bash(1),
and
builtins(7).
(file permissions) = (requested file permissions) & ~(umask value)
表 1.6. The umask value examples
umask | file permissions created | directory permissions created | usage |
---|---|---|---|
0022
|
-rw-r--r--
|
-rwxr-xr-x
|
writable only by the user |
0002
|
-rw-rw-r--
|
-rwxrwxr-x
|
writable by the group |
The Debian system uses a user private group (UPG) scheme as its default. A
UPG is created whenever a new user is added to the system. A UPG has the
same name as the user for which it was created and that user is the only
member of the UPG. UPG scheme makes it safe to set umask to
0002
since every user has their own private group. (In
some Unix variants, it is quite common to setup all normal users belonging
to a single users
group and is a good idea to set umask to 0022
for
security in such cases.)
![]() |
提示 |
---|---|
Enable UPG by putting " |
In order to make group permissions to be applied to a particular user, that
user needs to be made a member of the group using "sudo
vigr
" for /etc/group
and "sudo vigr
-s
" for /etc/gshadow
. You need to login after
logout (or run "exec newgrp
") to enable the new group
configuration.
![]() |
注意 |
---|---|
Alternatively, you may dynamically add users to groups during the
authentication process by adding " |
The hardware devices are just another kind of file on the Debian system. If you have problems accessing devices such as CD-ROM and USB memory stick from a user account, you should make that user a member of the relevant group.
Some notable system-provided groups allow their members to access particular
files and devices without root
privilege.
表 1.7. List of notable system-provided groups for file access
group | description for accessible files and devices |
---|---|
dialout
|
full and direct access to serial ports ("/dev/ttyS[0-3] ")
|
dip
|
limited access to serial ports for Dialup IP connection to trusted peers |
cdrom
|
CD-ROM, DVD+/-RW drives |
audio
|
audio device |
video
|
video device |
scanner
|
scanner(s) |
adm
|
system monitoring logs |
staff
|
some directories for junior administrative work:
"/usr/local ", "/home "
|
![]() |
提示 |
---|---|
You need to belong to the |
Some notable system-provided groups allow their members to execute
particular commands without root
privilege.
表 1.8. List of notable system provided groups for particular command executions
group | accessible commands |
---|---|
sudo
|
execute sudo without their password
|
lpadmin
|
execute commands to add, modify, and remove printers from printer databases |
For the full listing of the system provided users and groups, see the recent
version of the "Users and Groups" document in
"/usr/share/doc/base-passwd/users-and-groups.html
"
provided by the base-passwd
package.
See passwd(5), group(5), shadow(5), newgrp(1), vipw(8), vigr(8), and pam_group(8) for management commands of the user and group system.
GNU/Linux 文件有三種類型的時間戳。
![]() |
注意 |
---|---|
ctime 不是文件創建時間。 |
覆蓋一個文件,將會改變該文件所有的 mtime, ctime, 和 atime 屬性。
改變文件的所有者或者權限,將改變文件的 ctime 和 atime 屬性。
讀一個文件,將改變文件的 atime。
![]() |
注意 |
---|---|
Even simply reading a file on the Debian system normally causes a file write
operation to update atime information in
the inode. Mounting a filesystem with
" |
Use touch(1) command to change timestamps of existing files.
For timestamps, the ls
command outputs different strings
under non-English locale ("fr_FR.UTF-8
") from under the
old one ("C
").
$ LANG=fr_FR.UTF-8 ls -l foo -rw-rw-r-- 1 penguin penguin 0 oct. 16 21:35 foo $ LANG=C ls -l foo -rw-rw-r-- 1 penguin penguin 0 Oct 16 21:35 foo
![]() |
提示 |
---|---|
See 第 9.2.5 节 “Customized display of time and date” to customize
" |
There are two methods of associating a file "foo
" with a
different filename "bar
".
Duplicate name for an existing file
"ln foo bar
"
Special file that points to another file by name
"ln -s foo bar
"
See the following example for changes in link counts and the subtle
differences in the result of the rm
command.
$ umask 002 $ echo "Original Content" > foo $ ls -li foo 1449840 -rw-rw-r-- 1 penguin penguin 17 Oct 16 21:42 foo $ ln foo bar # hard link $ ln -s foo baz # symlink $ ls -li foo bar baz 1449840 -rw-rw-r-- 2 penguin penguin 17 Oct 16 21:42 bar 1450180 lrwxrwxrwx 1 penguin penguin 3 Oct 16 21:47 baz -> foo 1449840 -rw-rw-r-- 2 penguin penguin 17 Oct 16 21:42 foo $ rm foo $ echo "New Content" > foo $ ls -li foo bar baz 1449840 -rw-rw-r-- 1 penguin penguin 17 Oct 16 21:42 bar 1450180 lrwxrwxrwx 1 penguin penguin 3 Oct 16 21:47 baz -> foo 1450183 -rw-rw-r-- 1 penguin penguin 12 Oct 16 21:48 foo $ cat bar Original Content $ cat baz New Content
The hardlink can be made within the same filesystem and shares the same
inode number which the "-i
" option with
ls(1)
reveals.
The symlink always has nominal file access permissions of
"rwxrwxrwx
", as shown in the above example, with the
effective access permissions dictated by permissions of the file that it
points to.
![]() |
小心 |
---|---|
It is generally a good idea not to create complicated symbolic links or hardlinks at all unless you have a very good reason. It may cause nightmares where the logical combination of the symbolic links results in loops in the filesystem. |
![]() |
注意 |
---|---|
It is generally preferable to use symbolic links rather than hardlinks unless you have a good reason for using a hardlink. |
The ".
" directory links to the directory that it appears
in, thus the link count of any new directory starts at 2. The
"..
" directory links to the parent directory, thus the
link count of the directory increases with the addition of new
subdirectories.
If you are just moving to Linux from Windows, it soon becomes clear how well-designed the filename linking of Unix is, compared with the nearest Windows equivalent of "shortcuts". Because it is implemented in the filesystem, applications can't see any difference between a linked file and the original. In the case of hardlinks, there really is no difference.
A named pipe is a file that acts like a pipe. You put something into the file, and it comes out the other end. Thus it's called a FIFO, or First-In-First-Out: the first thing you put in the pipe is the first thing to come out the other end.
If you write to a named pipe, the process which is writing to the pipe
doesn't terminate until the information being written is read from the
pipe. If you read from a named pipe, the reading process waits until there
is nothing to read before terminating. The size of the pipe is always zero
--- it does not store data, it just links two processes like the
functionality offered by the shell "|
" syntax. However,
since this pipe has a name, the two processes don't have to be on the same
command line or even be run by the same user. Pipes were a very influential
innovation of Unix.
嘗試下列例子
$ cd; mkfifo mypipe $ echo "hello" >mypipe & # put into background [1] 8022 $ ls -l mypipe prw-rw-r-- 1 penguin penguin 0 Oct 16 21:49 mypipe $ cat mypipe hello [1]+ Done echo "hello" >mypipe $ ls mypipe mypipe $ rm mypipe
Sockets are used extensively by all the Internet communication, databases, and the operating system itself. It is similar to the named pipe (FIFO) and allows processes to exchange information even between different computers. For the socket, those processes do not need to be running at the same time nor to be running as the children of the same ancestor process. This is the endpoint for the inter process communication (IPC). The exchange of information may occur over the network between different hosts. The two most common ones are the Internet socket and the Unix domain socket.
![]() |
提示 |
---|---|
" |
設備文件包括系統的物理設備和虛擬設備,如硬盤、顯卡、顯示屏、鍵盤。虛擬設備的一個例子是控制檯,用“/dev/console
”來描述。
設備文件有兩種類型。
字符設備
每次訪問一個字符
一個字符等於一個字節
如鍵盤、串口…
塊設備
通過更大的單元–塊,進行訪問
一個塊>一個字節
如硬盤等…
你可以讀寫塊設備文件,儘管該文件可能包含二進制數據,讀取後顯示出無法理解的亂碼。向文件寫入數據,有時可以幫助定位硬件連接故障。比如,你可以將文本文件導入打印機設備“/dev/lp0
”,或者將調製解調命令發送到合適的串口“/dev/ttyS0
”。但是,除非這些操作都小心完成,否則可能會導致一場大災難。所以要特別小心。
![]() |
注意 |
---|---|
常規訪問打印機,使用lp(1)。 |
設備的節點數可以通過執行ls(1)得到,如下所示。
$ ls -l /dev/sda /dev/sr0 /dev/ttyS0 /dev/zero brw-rw---T 1 root disk 8, 0 Oct 16 20:57 /dev/sda brw-rw---T+ 1 root cdrom 11, 0 Oct 16 21:53 /dev/sr0 crw-rw---T 1 root dialout 4, 64 Oct 16 20:57 /dev/ttyS0 crw-rw-rw- 1 root root 1, 5 Oct 16 20:57 /dev/zero
"/dev/sda
"的主設備號是8,次設備號是0。它可以被disk
羣組的用戶讀寫。
"/dev/sr0
"的主設備號是11,次設備號是0。它可以被cdrom
羣組的用戶讀寫。
"/dev/ttyS0
"的主設備號是4,次設備號是64。它可以被dailout
羣組的用戶讀寫。
"/dev/zero
"的主設備號是1,次設備號是5。它可以被任意用戶讀寫。
在現代Linux系統中,處在"/dev
"之下的文件系統會自動被udev()機制填充。
還有一些特別的設備文件。
表 1.10. 特別設備文件列表
設備文件 | 操作 | 響應描述 |
---|---|---|
/dev/null
|
讀取 | 返回“文件結尾字符(EOF)“ |
/dev/null
|
寫入 | 無返回(一個無底的數據轉存深淵) |
/dev/zero
|
讀取 |
返回"\0 空字符"(與ASCII中的數字0不同)
|
/dev/random
|
讀取 | 從真隨機數產生器返回一個隨機字符,供應真熵(緩慢) |
/dev/urandom
|
讀取 | 從能夠安全加密的僞隨機數產生器返回一個隨機字符 |
/dev/full
|
寫入 | 返回磁盤已滿(ENOSPC)錯誤 |
這些特別設備文件經常和shell數據重定向聯合使用(參考第 1.5.8 节 “Typical command sequences and shell redirection”)。
procfs和sysfs兩個僞文件系統,分別加載於"/proc
"和"/sys
"之上,將內核中的數據結構暴露給用戶空間。或者說,這些條目是虛擬的,他們打開了深入瞭解操作系統運行的方便之門。
目錄"/proc
"爲每個正在運行的進程提供了一個子目錄,目錄的名字就是進程標識符(PID)。需要讀取進程信息的系統工具,如ps(),可以從這個目錄結構獲得信息。
"/proc/sys
"之下的目錄,包含了可以更改某些內核運行參數的接口。(你也可以使用專門的sysctl()命令修改,或者使用其預加載/配置文件"/etc/sysctl.conf
"。)
當人們看到這個特別大的文件"/proc/kcore
"時,常常會驚慌失措。這個文件於你的的電腦內存大小相差不多。它被用來調試內核。它是一個虛擬文件,指向系統內存,所以不必擔心它的大小。
"/sys
"以下的目錄包含了內核輸出的數據結構,它們的屬性,以及它們之間的鏈接。它同時也包含了改變某些內核運行時參數的接口。
參考"proc.txt(.gz)
","sysfs.txt(.gz)
",以及其他相關的Linux內核文檔("/usr/share/doc/linux-doc-*/Documentation/filesystems/*
"),這些文件由linux-doc-*
軟件包提供。
tmpfs是一個臨時文件系統,它的文件都保存在虛擬內存中。必要時,位於內存頁緩存的tmpfs數據可能被交換到硬盤中的交換分區。
系統啓動早期階段,"/run
"目錄掛載爲tmpfs。這樣即使"/
"掛載爲只讀,它也是可以被寫入的。它爲過渡態文件提供了新的存儲空間,同時也替代了Filesystem Hierarchy
Standar2.3版中說明的目錄位置:
"/var/run
" → "/run
"
"/var/lock
" → "/run/lock
"
"/dev/shm
" → "/run/shm
"
參考"tmpfs.txt(.gz)
",
文件位於Linux內核文檔("/usr/share/doc/linux-doc-*/Documentation/filesystems/*
")目錄之下,由軟件包linux-doc-*
提供。
Midnight Commander (MC) is a GNU "Swiss army knife" for the Linux console and other terminal environments. This gives newbie a menu driven console experience which is much easier to learn than standard Unix commands.
You may need to install the Midnight Commander package which is titled
"mc
" by the following.
$ sudo apt-get install mc
Use the mc(1) command to explore the Debian system. This is the best way to learn. Please explore few interesting locations just using the cursor keys and Enter key.
"/etc
" and its subdirectories
"/var/log
" and its subdirectories
"/usr/share/doc
" and its subdirectories
"/sbin
" and "/bin
"
In order to make MC to change working directory upon exit and
cd
to the directory, I suggest to modify
"~/.bashrc
" to include a script provided by the
mc
package.
. /usr/lib/mc/mc.sh
See
mc(1)
(under the "-P
" option) for the reason. (If you do not
understand what exactly I am talking here, you can do this later.)
MC can be started by the following.
$ mc
MC takes care of all file operations through its menu, requiring minimal user effort. Just press F1 to get the help screen. You can play with MC just by pressing cursor-keys and function-keys.
![]() |
注意 |
---|---|
In some consoles such as
gnome-terminal(1),
key strokes of function-keys may be stolen by the console program. You can
disable these features by "Edit" → "Keyboard Shortcuts" for
|
If you encounter character encoding problem which displays garbage
characters, adding "-a
" to MC's command line may help
prevent problems.
If this doesn't clear up your display problems with MC, see 第 9.4.6 节 “The terminal configuration”.
The default is two directory panels containing file lists. Another useful mode is to set the right window to "information" to see file access privilege information, etc. Following are some essential keystrokes. With the gpm(8) daemon running, one can use a mouse on Linux character consoles, too. (Make sure to press the shift-key to obtain the normal behavior of cut and paste in MC.)
表 1.11. MC 快捷鍵綁定
快捷鍵 | 鍵綁定功能 |
---|---|
F1
|
幫助菜單 |
F3
|
internal file viewer |
F4
|
internal editor |
F9
|
activate pull down menu |
F10
|
exit Midnight Commander |
Tab
|
在兩個窗口間移動 |
Insert 或 Ctrl-T
|
mark file for a multiple-file operation such as copy |
Del
|
delete file (be careful---set MC to safe delete mode) |
Cursor keys | self-explanatory |
cd
command changes the directory shown on the selected
screen.
Ctrl-Enter
or Alt-Enter
copies a
filename to the command line. Use this with
cp(1)
and
mv(1)
commands together with command-line editing.
Alt-Tab
shows shell filename expansion choices.
One can specify the starting directory for both windows as arguments to MC;
for example, "mc /etc /root
".
Esc
+ n-key
→ Fn
(i.e., Esc
+ 1
→
F1
, etc.; Esc
+ 0
→
F10
)
Pressing Esc
before the key has the same effect as
pressing the Alt
and the key together.; i.e., type
Esc
+ c
for Alt-C
.
Esc
is called meta-key and sometimes noted as
"M-
".
The internal editor has an interesting cut-and-paste scheme. Pressing
F3
marks the start of a selection, a second
F3
marks the end of selection and highlights the
selection. Then you can move your cursor. If you press F6, the selected
area is moved to the cursor location. If you press F5, the selected area is
copied and inserted at the cursor location. F2
saves the
file. F10
gets you out. Most cursor keys work
intuitively.
This editor can be directly started on a file using one of the following commands.
$ mc -e filename_to_edit
$ mcedit filename_to_edit
This is not a multi-window editor, but one can use multiple Linux consoles to achieve the same effect. To copy between windows, use Alt-F<n> keys to switch virtual consoles and use "File→Insert file" or "File→Copy to file" to move a portion of a file to another file.
This internal editor can be replaced with any external editor of choice.
Also, many programs use the environment variables
"$EDITOR
" or "$VISUAL
" to decide which
editor to use. If you are uncomfortable with
vim(1)
or
nano(1)
initially, you may set these to "mcedit
" by adding the
following lines to "~/.bashrc
".
export EDITOR=mcedit export VISUAL=mcedit
I do recommend setting these to "vim
" if possible.
If you are uncomfortable with vim(1), you can keep using mcedit(1) for most system maintenance tasks.
MC is a very smart viewer. This is a great tool for searching words in
documents. I always use this for files in the
"/usr/share/doc
" directory. This is the fastest way to
browse through masses of Linux information. This viewer can be directly
started using one of the following commands.
$ mc -v path/to/filename_to_view
$ mcview path/to/filename_to_view
Press Enter on a file, and the appropriate program handles the content of the file (see 第 9.3.11 节 “Customizing program to be started”). This is a very convenient MC feature.
表 1.12. The reaction to the enter key in MC
file type | reaction to enter key |
---|---|
executable file | execute command |
man file | pipe content to viewer software |
html file | pipe content to web browser |
"*.tar.gz " 和 "*.deb " 文件
|
browse its contents as if subdirectory |
In order to allow these viewer and virtual file features to function, viewable files should not be set as executable. Change their status using chmod(1) or via the MC file menu.
MC can be used to access files over the Internet using FTP. Go to the menu
by pressing F9
, then type "p
" to
activate the FTP virtual filesystem. Enter a URL in the form
"username:passwd@hostname.domainname
", which retrieves a
remote directory that appears like a local one.
Try "[http.us.debian.org/debian]" as the URL and browse the Debian archive.
Although MC enables you to do almost everything, it is very important for you to learn how to use the command line tools invoked from the shell prompt and become familiar with the Unix-like work environment.
You can select your login shell with chsh(1).
表 1.13. List of shell programs
軟件包 | 流行度 | 大小 | POSIX shell | 說明 |
---|---|---|---|---|
bash
|
V:859, I:999 | 5786 | Yes | Bash: the GNU Bourne Again SHell (de facto standard) |
tcsh
|
V:12, I:45 | 1279 | No | TENEX C Shell: an enhanced version of Berkeley csh |
dash
|
V:906, I:976 | 200 | Yes | Debian Almquist Shell, good for shell script |
zsh
|
V:34, I:65 | 2088 | Yes | Z shell: the standard shell with many enhancements |
mksh
|
V:3, I:12 | 1260 | Yes | A version of the Korn shell |
csh
|
V:2, I:12 | 327 | No | OpenBSD C Shell, a version of Berkeley csh |
sash
|
V:1, I:5 | 973 | Yes | Stand-alone shell with builtin
commands (Not meant for standard "/bin/sh ")
|
ksh
|
V:5, I:23 | 3236 | Yes | the real, AT&T version of the Korn shell |
rc
|
V:0, I:4 | 154 | No | implementation of the AT&T Plan 9 rc shell |
posh
|
V:0, I:0 | 182 | Yes |
Policy-compliant Ordinary SHell (pdksh derivative)
|
![]() |
提示 |
---|---|
Although POSIX-like shells share the basic syntax, they can differ in behavior for things as basic as shell variables and glob expansions. Please check their documentation for details. |
In this tutorial chapter, the interactive shell always means
bash
.
你可以通過“~/.bashrc
”來定製bash(1)的行爲。
嘗試下列例子。
# enable bash-completion if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi # CD upon exiting MC . /usr/lib/mc/mc.sh # set CDPATH to a good one CDPATH=.:/usr/share/doc:~:~/Desktop:~ export CDPATH PATH="${PATH+$PATH:}/usr/sbin:/sbin" # set PATH so it includes user's private bin if it exists if [ -d ~/bin ] ; then PATH="~/bin${PATH+:$PATH}" fi export PATH EDITOR=vim export EDITOR
![]() |
提示 |
---|---|
你可以在第 9 章 System tips中的第 9.2.7 节 “Colorized commands”找到更多關於 |
![]() |
提示 |
---|---|
The |
在類Unix環境,有一些具有特殊含義的按鍵。請注意,普通的Linux字符控制檯,只有左手邊的Ctrl
和Alt
鍵可以正常工作。其中有幾個值得記住的按鍵。
表 1.14. bash的按鍵綁定列表
快捷鍵 | 描述 |
---|---|
Ctrl-U
|
刪除光標前到行首的字符 |
Ctrl-H
|
刪除光標前的一個字符 |
Ctrl-D
|
終止輸入(如果你在使用shell,則退出shell) |
Ctrl-C
|
終止一個正在運行的程序 |
Ctrl-Z
|
通過將程序移動到後臺來暫停程序 |
Ctrl-S
|
停止屏幕輸出 |
Ctrl-Q
|
激活屏幕輸出 |
Ctrl-Alt-Del
|
重啓/關閉系統,參見inittab(5) |
Left-Alt-key (或Windows-key )
|
Emacs和相似UI的元鍵(meta-key) |
Up-arrow
|
開始在bash 中的命令歷史搜索
|
Ctrl-R
|
開始在bash 中的增量命令歷史搜索
|
Tab
|
在 bash 命令行中補全文件名
|
Ctrl-V Tab
|
在 bash 命令行中輸出 Tab 而不是進行補全
|
![]() |
提示 |
---|---|
|
Unix類型的鼠標操作基於3鍵的鼠標系統。
表 1.15. Unix樣式的鼠標操作列表
操作 | 響應 |
---|---|
左擊並拖動鼠標 | 選擇並複製到剪貼板 |
單擊左鍵 | select the start of selection |
單擊右鍵 | select the end of selection and copy to the clipboard |
單擊中鍵 | 粘貼剪切板的內容到光標處 |
The center wheel on the modern wheel mouse is considered middle mouse button and can be used for middle-click. Clicking left and right mouse buttons together serves as the middle-click under the 2 button mouse system situation. In order to use a mouse in Linux character consoles, you need to have gpm(8) running as daemon.
The
less(1)
command is the enhanced pager (file content browser). It reads the file
specified by its command argument or its standard input. Hit
"h
" if you need help while browsing with the
less
command. It can do much more than
more(1)
and can be supercharged by executing "eval $(lesspipe)
"
or "eval $(lessfile)
" in the shell startup script. See
more in "/usr/share/doc/lessf/LESSOPEN
". The
"-R
" option allows raw character output and enables ANSI
color escape sequences. See
less(1).
You should become proficient in one of variants of Vim or Emacs programs which are popular in the Unix-like system.
I think getting used to Vim commands is the right thing to do, since
Vi-editor is always there in the Linux/Unix world. (Actually, original
vi
or new nvi
are programs you find
everywhere. I chose Vim instead for newbie since it offers you help through
F1
key while it is similar enough and more powerful.)
If you chose either Emacs or XEmacs instead as your choice of the editor, that is another good choice indeed, particularly for programming. Emacs has a plethora of other features as well, including functioning as a newsreader, directory editor, mail program, etc. When used for programming or editing shell scripts, it intelligently recognizes the format of what you are working on, and tries to provide assistance. Some people maintain that the only program they need on Linux is Emacs. Ten minutes learning Emacs now can save hours later. Having the GNU Emacs manual for reference when learning Emacs is highly recommended.
All these programs usually come with tutoring program for you to learn them
by practice. Start Vim by typing "vim
" and press
F1-key. You should at least read the first 35 lines. Then do the online
training course by moving cursor to "|tutor|
" and
pressing Ctrl-]
.
![]() |
注意 |
---|---|
Good editors, such as Vim and Emacs, can handle UTF-8 and other exotic encoding texts correctly. It is a good idea to use the X environment in the UTF-8 locale and to install required programs and fonts to it. Editors have options to set the file encoding independent of the X environment. Please refer to their documentation on multibyte text. |
Debian有許多不同的編輯器。我們建議安裝上面提到的vim
軟件包。
Debian通過命令“/usr/bin/editor
”提供了對系統默認編輯器的統一訪問,因此其它程序(例如reportbug(1))可以調用它。你可以通過下列命令改變它。
$ sudo update-alternatives --config editor
對於新手,我建議使用“/usr/bin/vim.basic
”代替“/usr/bin/vim.tiny
”,因爲它支持格式高亮。
![]() |
提示 |
---|---|
許多程序使用環境變量“ |
你可以通過“~/.vimrc
”來定製vim(1)的行爲。
嘗試下列例子
" ------------------------------- " Local configuration " set nocompatible set nopaste set pastetoggle=<f2> syn on if $USER == "root" set nomodeline set noswapfile else set modeline set swapfile endif " filler to avoid the line above being recognized as a modeline " filler " filler
shell命令的輸出有可能滾動出了屏幕,並可能導致你無法再查看到它。將shell活動記錄到文件中再來回顧它是個不錯的主意。當你執行任何系統管理任務時,這種記錄是必不可少的。
記錄shell活動的基本方法是在script(1)下運行shell。
嘗試下列例子
$ script Script started, file is typescript
在script
下使用任何shell命令。
按Ctrl-D
來退出script
。
$ vim typescript
讓我們來學習基本的Unix命令。在這裏,我指的是一般意義上的“UNIX”。任何UNIX克隆系統通常都會提供等價的命令。Debian系統也不例外。如果有一些命令不像你想的那樣起作用,請不要擔心。如果shell中使用了別名
,其對應的命令輸出會不同。這些例子並不意味着要以這個順序來執行。
嘗試使用非特權用戶賬號來使用下列的命令。
表 1.16. 基本的Unix命令列表
命令 | 說明 |
---|---|
pwd
|
顯示當前/工作目錄的名稱 |
whoami
|
顯示當前的用戶名 |
id
|
顯示當前用戶的身份(名稱、uid、gid和相關組) |
file <foo>
|
顯示“<foo> ”文件的文件類型
|
type -p <commandname>
|
顯示“<commandname> ”命令的文件所處位置
|
which <commandname>
|
同上 |
type <commandname>
|
顯示“<commandname> ”命令的相關信息
|
apropos <key-word>
|
查找與“<key-word> ”有關的命令
|
man -k <key-word>
|
同上 |
whatis <commandname>
|
用一行解釋 “<commandname> ” 命令
|
man -a <commandname>
|
顯示“<commandname> ”命令的解釋(Unix風格)
|
info <commandname>
|
顯示“<commandname> ”命令相當長的解釋(GNU風格)
|
ls
|
顯示目錄內容(不包含以 . 點號開頭的文件和目錄) |
ls -a
|
顯示目錄內容(包含所有文件和目錄) |
ls -A
|
顯示目錄內容(包含幾乎所有文件和目錄,除了“.. ”和“. ”)
|
ls -la
|
顯示所有的目錄內容,幷包含詳細的信息 |
ls -lai
|
顯示所有的目錄內容,幷包含inode和詳細的信息 |
ls -d
|
顯示當前目錄下的所有目錄 |
tree
|
使用樹狀圖顯示目錄內容 |
lsof <foo>
|
list open status of file "<foo> "
|
lsof -p <pid>
|
list files opened by the process ID: "<pid> "
|
mkdir <foo>
|
在當前目錄中建立新目錄“<foo> ”
|
rmdir <foo>
|
刪除當前目錄中的“<foo> ”目錄
|
cd <foo>
|
切換到當前目錄下或變量“$CDPATH ”中的“<foo> ”目錄
|
cd /
|
切換到根目錄 |
cd
|
切換到當前用戶的家目錄 |
cd /<foo>
|
切換到絕對路徑爲“/<foo> ”的目錄
|
cd ..
|
切換到上一級目錄 |
cd ~<foo>
|
切換到用戶“<foo> ”的家目錄
|
cd -
|
切換到之前的目錄 |
</etc/motd pager
|
使用默認的分頁顯示程序來顯示“/etc/motd ”的內容
|
touch <junkfile>
|
建立一個空文件“<junkfile> ”
|
cp <foo> <bar>
|
將一個現有文件“<foo> ”複製到一個新文件“<bar> ”
|
rm <junkfile>
|
刪除文件“<junkfile> ”
|
mv <foo> <bar>
|
將一個現有文件“<foo> ”重命名成“<bar> ”(“<bar> ”必須不存在)
|
mv <foo> <bar>
|
將一個現有文件“<foo> ”移動到新的位置“<bar>/<foo> ”(必須存在“<bar> ”目錄)
|
mv <foo> <bar>/<baz>
|
移動一個現有文件“<foo> ”到新位置並重命名爲“<bar>/<baz> ”(必須存在“bar ”目錄,且不存在“bar>/<baz> ”目錄)
|
chmod 600 <foo>
|
使其他人無法讀寫現有文件“<foo> ”(並且所有人都無法執行該文件)
|
chmod 644 <foo>
|
使其他人對現有文件“<foo> ”可讀但不可寫(並且所有人都無法執行該文件)
|
chmod 755 <foo>
|
使其他人對“<foo> ”可讀而不可寫(並且所有人都能執行該文件)
|
find . -name <pattern>
|
使用 shell “<pattern> ” 查找匹配的文件名(速度較慢)
|
locate -d . <pattern>
|
使用 shell “<pattern> ” 查找匹配的文件名(速度較快,使用定期生成的數據庫)
|
grep -e "<pattern>" *.html
|
在當前目錄下以“.html ”結尾的所有文件中,查找匹配“<pattern> ”的文件並顯示
|
top
|
全屏顯示進程信息,輸入“q ”退出
|
ps aux | pager
|
顯示所有正在運行的進程的信息(BSD風格) |
ps -ef | pager
|
顯示所有正在運行的進程的信息(Unix system-V風格) |
ps aux | grep -e "[e]xim4*"
|
顯示所有正在運行“exim ”和“exim4 ”的進程
|
ps axf | pager
|
顯示所有正在運行的進程的信息(ASCII風格) |
kill <1234>
|
殺死ID爲“<1234>”的進程 |
gzip <foo>
|
使用 Lempel-Ziv
編碼(LZ77)將“<foo> ”壓縮爲“<foo>.gz ”
|
gunzip <foo>.gz
|
將“<foo>.gz ”解壓爲“<foo> ”
|
bzip2 <foo>
|
使用 Burrows-Wheeter 塊排序壓縮算法和 Huffman
編碼將“<foo> ”壓縮爲“<foo>.bz2 ”(壓縮效果比gzip 更好)
|
bunzip2 <foo>.bz2
|
將“<foo>.bz2 ”解壓爲“<foo> ”
|
xz <foo>
|
使用 Lempel-Ziv-Markov
鏈算法將“<foo> ”壓縮爲“<foo>.xz ”(壓縮效果比bzip2 更好)
|
unxz <foo>.xz
|
將“<foo>.xz ”解壓爲“<foo> ”
|
tar -xvf <foo>.tar
|
從“<foo>.tar ”檔案中提取文件
|
tar -xvzf <foo>.tar.gz
|
從被gzip壓縮過的“<foo>.tar.gz ”檔案中提取文件
|
tar -xvjf <foo>.tar.bz2
|
從“<foo>.tar.bz2 ”檔案中提取文件
|
tar -xvJf <foo>.tar.xz
|
從“<foo>.tar.xz ”檔案中提取文件
|
tar -cvf <foo>.tar <bar>/
|
將目錄“<bar>/ ”中的內容打包到“<foo>.tar ”檔案中
|
tar -cvzf <foo>.tar.gz <bar>/
|
將目錄“<bar>/ ”中的內容打包到被壓縮的“<foo>.tar.gz ”檔案中
|
tar -cvjf <foo>.tar.bz2 <bar>/
|
將目錄“<bar>/ ”中的內容打包到“<foo>.tar.bz2 ”檔案中
|
tar -cvJf <foo>.tar.xz <bar>/
|
將目錄”<bar>/ “中的內容打包到”<foo>.tar.xz “檔案中
|
zcat README.gz | pager
|
使用默認的分頁顯示程序來顯示“README.gz ”壓縮包中的內容
|
zcat README.gz > foo
|
將“README.gz ”解壓後的內容輸出到文件“foo ”中
|
zcat README.gz >> foo
|
將“README.gz ”解壓後的內容添加到文件“foo ”的末尾(如果文件不存在,則會先建立該文件)
|
![]() |
注意 |
---|---|
Unix有一個慣例,以“ |
![]() |
注意 |
---|---|
對於 |
![]() |
注意 |
---|---|
基本的 Debian
系統的默認分頁顯示程序是more(1),它無法往回滾動。通過命令“ |
![]() |
注意 |
---|---|
The " |
作爲訓練,請使用上述的命令來遍歷目錄並探究系統。如果你有任何有關控制臺命令的問題,請務必閱讀手冊。
嘗試下列例子
$ man man $ man bash $ man builtins $ man grep $ man ls
手冊的風格可能讓人有點難以習慣,因爲它們都相當簡潔,尤其是比較老舊、非常傳統的那些手冊。但是,一旦你習慣了它,你來欣賞它們的簡潔。
請注意,許多類Unix命令(包含來自 GNU 和 BSD 的)都可以顯示簡短的幫助信息,你可以使用下列的其中一種方式來查看它(有時不帶任何參數也可以)。
$ <commandname> --help $ <commandname> -h
現在,你對如何使用 Debian 系統已經有一些感覺了。讓我們更深入瞭解 Debian 系統的命令執行機制。在這裏,我將爲新手做一般的講解。精確的解釋參見bash(1)。
一般的命令由有序的組件構成。
設置變量值(可選)
命令名
參數(可選)
重定向(可選:>
, >>
,
<
, <<
等等)
控制操作(可選:&&
, ||
, <換行符>
, ;
, &
, (
,
)
)
一些環境變量的值會改變部分Unix命令的行爲。
環境變量的默認值由PAM系統初始化,其中一些會被某些應用程序重新設定。
顯示管理器(例如gdm3
)會重新設定環境變量。
The shell in its start up codes resets environment variables in
"~/.bash_profile
" and "~/.bashrc
".
The full locale value given to "$LANG
" variable consists
of 3 parts: "xx_YY.ZZZZ
".
表 1.17. The 3 parts of locale value
locale value | 說明 |
---|---|
xx
|
ISO 639 語言代碼(小寫)例如“en” |
YY
|
ISO 3166 國家代碼(大寫)例如“US” |
ZZZZ
|
編碼,總是設置爲“UTF-8” |
對於語言代碼和國家代碼,參加“info gettext
”中的相關描述。
對於現代 Debian 系統中的編碼,你應該總是設定爲UTF-8
,除非你有足夠的理由和背景知識並且特別想使用過時的編碼。
For fine details of the locale configuration, see 第 8.3 节 “The locale”.
![]() |
注意 |
---|---|
“ |
表 1.18. locale 推薦的列表
locale 推薦 | 語言(地區) |
---|---|
en_US.UTF-8
|
英語(美國) |
en_GB.UTF-8
|
英語(大不列顛) |
fr_FR.UTF-8
|
法語(法國) |
de_DE.UTF-8
|
德語(德國) |
it_IT.UTF-8
|
意大利語(意大利) |
es_ES.UTF-8
|
西班牙語(西班牙) |
ca_ES.UTF-8
|
加泰隆語(西班牙) |
sv_SE.UTF-8
|
瑞典語(瑞典) |
pt_BR.UTF-8
|
葡萄牙語(巴西) |
ru_RU.UTF-8
|
俄語(俄國) |
zh_CN.UTF-8
|
漢語(中華人民共和國) |
zh_TW.UTF-8
|
漢語(中國臺灣) |
ja_JP.UTF-8
|
日語(日本) |
ko_KR.UTF-8
|
韓語(韓國) |
vi_VN.UTF-8
|
越南語(越南) |
使用 shell 命令行按順序執行下列典型的命令。
$ date Sun Jun 3 10:27:39 JST 2007 $ LANG=fr_FR.UTF-8 date dimanche 3 juin 2007, 10:27:33 (UTC+0900)
這裏,date(1)程序執行時使用了與環境變量“$LANG
”不同的值。
大多數的命令在執行時並沒有預先定義環境變量。對於上面的例子,你也可以選擇如下的方式。
$ LANG=fr_FR.UTF-8 $ date dimanche 3 juin 2007, 10:27:33 (UTC+0900)
As you can see here, the output of command is affected by the environment variable to produce French output. If you want the environment variable to be inherited to subprocesses (e.g., when calling shell script), you need to export it instead by the following.
$ export LANG
![]() |
注意 |
---|---|
When you use a typical console terminal, the " |
![]() |
提示 |
---|---|
When filing a bug report, running and checking the command under
" |
See
locale(5)
and
locale(7)
for "$LANG
" and related environment variables.
![]() |
注意 |
---|---|
I recommend you to configure the system environment just by the
" |
When you type a command into the shell, the shell searches the command in
the list of directories contained in the "$PATH
"
environment variable. The value of the "$PATH
"
environment variable is also called the shell's search path.
In the default Debian installation, the "$PATH
"
environment variable of user accounts may not include
"/sbin
" and "/usr/sbin
". For example,
the ifconfig
command needs to be issued with full path as
"/sbin/ifconfig
". (Similar ip
command
is located in "/bin
".)
You can change the "$PATH
" environment variable of Bash
shell by "~/.bash_profile
" or
"~/.bashrc
" files.
Many commands stores user specific configuration in the home directory and
changes their behavior by their contents. The home directory is identified
by the environment variable "$HOME
".
表 1.19. List of "$HOME
" values
value of "$HOME "
|
program execution situation |
---|---|
/
|
program run by the init process (daemon) |
/root
|
program run from the normal root shell |
/home/<normal_user>
|
program run from the normal user shell |
/home/<normal_user>
|
program run from the normal user GUI desktop menu |
/home/<normal_user>
|
program run as root with "sudo program "
|
/root
|
program run as root with "sudo -H program "
|
![]() |
提示 |
---|---|
Shell expands " |
Some commands take arguments. Arguments starting with
"-
" or "--
" are called options and
control the behavior of the command.
$ date Mon Oct 27 23:02:09 CET 2003 $ date -R Mon, 27 Oct 2003 23:02:40 +0100
Here the command-line argument "-R
" changes
date(1)
behavior to output RFC2822 compliant date
string.
Often you want a command to work with a group of files without typing all of them. The filename expansion pattern using the shell glob, (sometimes referred as wildcards), facilitate this need.
表 1.20. Shell glob patterns
shell glob pattern | description of match rule |
---|---|
*
|
filename (segment) not started with ". "
|
.*
|
filename (segment) started with ". "
|
?
|
exactly one character |
[…]
|
exactly one character with any character enclosed in brackets |
[a-z]
|
exactly one character with any character between "a " and
"z "
|
[^…]
|
exactly one character other than any character enclosed in brackets
(excluding "^ ")
|
嘗試下列例子
$ mkdir junk; cd junk; touch 1.txt 2.txt 3.c 4.h .5.txt ..6.txt $ echo *.txt 1.txt 2.txt $ echo * 1.txt 2.txt 3.c 4.h $ echo *.[hc] 3.c 4.h $ echo .* . .. .5.txt ..6.txt $ echo .*[^.]* .5.txt ..6.txt $ echo [^1-3]* 4.h $ cd ..; rm -rf junk
參見 glob(7)。
![]() |
注意 |
---|---|
Unlike normal filename expansion by the shell, the shell pattern
" |
![]() |
注意 |
---|---|
BASH can be tweaked to change its glob behavior with its shopt builtin
options such as " |
每個命令都會返回它的退出狀態(變量:“$?
”)作爲返回值。
嘗試下列例子。
$ [ 1 = 1 ] ; echo $? 0 $ [ 1 = 2 ] ; echo $? 1
![]() |
注意 |
---|---|
Please note that, in the logical context for the shell, success is treated as the logical TRUE which has 0 (zero) as its value. This is somewhat non-intuitive and needs to be reminded here. |
Let's try to remember following shell command idioms typed in one line as a part of shell command.
表 1.22. Shell command idioms
command idiom | 說明 |
---|---|
command &
|
在子 shell 的後臺 中執行
command
|
command1 | command2
|
通過管道將 command1 的標準輸出作爲
command2 的標準輸入(並行執行)
|
command1 2>&1 | command2
|
通過管道將 command1
的標準輸出和標準錯誤作爲 command2 的標準輸入(並行執行)
|
command1 ; command2
|
按順序執行 command1 和
command2
|
command1 && command2
|
執行 command1 ;如果成功,按順序執行
command2 (如果 command1 和 command2 都執行成功了,返回 success )
|
command1 || command2
|
執行 command1 ;如果不成功,按順序執行 command2 (如果
command1 或
command2 執行成功,返回 success )
|
command > foo
|
將 command 的標準輸出重定向到文件 foo (覆蓋)
|
command 2> foo
|
將 command 的標準錯誤重定向到文件 foo (覆蓋)
|
command >> foo
|
將 command 的標準輸出重定向到文件 foo (附加)
|
command 2>> foo
|
將 command 的標準錯誤重定向到文件 foo (附加)
|
command > foo 2>&1
|
將 command 的標準輸出和標準錯誤重定向到文件 foo
|
command < foo
|
將 command 的標準輸入重定向到文件 foo
|
command << delimiter
|
將 command
的標準輸入重定向到下面的命令行,直到遇到“delimiter ”(here document)
|
command <<- delimiter
|
將 command
的標準輸入重定向到下面的命令行,直到遇到“delimiter ”(here
document,命令行中開頭的製表符會被忽略)
|
Debian 系統是一個多任務的操作系統。後臺任務讓用戶能夠在一個 shell 中執行多個程序。後臺進程的管理涉及 shell
的內建命令:jobs
、fg
、bg
和
kill
。請閱讀 bash(1) 中的章節:“SIGNALS”、“JOB CONTROL” 和
“builtins(1)”。
嘗試下列例子
$ </etc/motd pager
$ pager </etc/motd
$ pager /etc/motd
$ cat /etc/motd | pager
儘管4個 shell 重定向的例子都會顯示相同的結果,但最後一個例子毫無意義地運行了額外的 cat
命令浪費了資源。
shell 允許你使用 exec
通過任意一個文件描述符來打開文件。
$ echo Hello >foo $ exec 3<foo 4>bar # open files $ cat <&3 >&4 # redirect stdin to 3, stdout to 4 $ exec 3<&- 4>&- # close files $ cat bar Hello
預定義的文件描述符0-2。
你可以爲經常使用的命令設置一個別名。
嘗試下列例子
$ alias la='ls -la'
現在,“la
”是“ls
-al
”的簡寫形式,並同樣會以長列表形式列出所有的文件。
你可以使用 alias
來列出所有的別名(參見
bash(1)
中的“SHELL BUILTIN COMMANDS”)。
$ alias ... alias la='ls -la'
你可以使用 type
來確認命令的準確路徑或類型(參見
bash(1)
中的“SHELL BUILTIN COMMANDS”)。
嘗試下列例子
$ type ls ls is hashed (/bin/ls) $ type la la is aliased to ls -la $ type echo echo is a shell builtin $ type file file is /usr/bin/file
Here ls
was recently searched while
"file
" was not, thus "ls
" is "hashed",
i.e., the shell has an internal record for the quick access to the location
of the "ls
" command.
在類 Unix 的工作環境中,文本處理是通過使用管道組成的標準文本處理工具鏈完成的。這是另一個重要的 Unix 創新。
這裏有一些在類 Unix 系統中經常使用到的標準文本處理工具。
沒有使用正則表達式:
cat(1) 連接文件並輸出全部的內容。
tac(1) 連接文件並反向輸出。
cut(1) selects parts of lines and outputs.
head(1) 輸出文件的開頭。
tail(1) 輸出文件的末尾。
sort(1) 對文本文件的行進行排序。
uniq(1) 從已排序的文件中移除相同的行。
tr(1) 轉換或刪除字符。
diff(1) 對文件的行進行對比。
使用基礎的正則表達式( BRE ):
grep(1) matches text with patterns.
ed(1) 是一個原始行編輯器。
sed(1) 是一個流編輯器。
vim(1) 是一個屏幕編輯器。
emacs(1) 是一個屏幕編輯器。(有些擴展的 BRE )
使用擴展的正則表達式( ERE ):
egrep(1) matches text with patterns.
awk(1) 進行簡單的文本處理。
tcl(3tcl) 可以進行任何你想得到的文本處理:參見 re_syntax(3) 。經常與 tk(3tk) 一起使用。
perl(1) 可以進行任何你想得到的文本處理。參見 perlre(1) 。
pcregrep(1)
from the pcregrep
package matches text with Perl Compatible Regular Expressions
(PCRE) pattern.
帶有 re
模塊的
python(1)
可以進行任何你想得到的文本處理。參見“/usr/share/doc/python/html/index.html
”。
如果你不確定這些命令究竟做了什麼,請使用“man command
” 來自己把它搞清楚吧。
![]() |
注意 |
---|---|
Sort order and range expression are locale dependent. If you wish to obtain
traditional behavior for a command, use C
locale instead of UTF-8 ones by
prepending command with " |
![]() |
注意 |
---|---|
Perl 正則表達式(
perlre(1)
)、Perl 兼容正則表達式(PCRE)
和 Python 的 |
Regular expressions are used in many text processing tools. They are analogous to the shell globs, but they are more complicated and powerful.
The regular expression describes the matching pattern and is made up of text characters and metacharacters.
元字符僅僅是帶有特殊含義的字符。它們有兩種主要的形式,BRE 和 ERE ,使用哪種取決於上述的文本工具。
表 1.24. BRE 和 ERE 中的元字符
BRE | ERE | 正則表達式的描述 |
---|---|---|
\ . [ ] ^ $ *
|
\ . [ ] ^ $ *
|
通用的元字符 |
\+ \? \( \) \{ \} \|
|
BRE 獨有的“\ ”跳脫元字符
|
|
+ ? ( ) { } |
|
ERE only non-"\ " escaped metacharacters
|
|
c
|
c
|
匹配非元字符 “c ”
|
\c
|
\c
|
匹配一個字面意義上的字符 “c ”,即使 “c ” 本身是元字符
|
.
|
.
|
匹配任意字符,包括換行符 |
^
|
^
|
字符串的開始位置 |
$
|
$
|
字符串的結束位置 |
\<
|
\<
|
單詞的開始位置 |
\>
|
\>
|
單詞的結束位置 |
[abc…]
|
[abc…]
|
匹配在 “abc... ” 中的任意字符
|
[^abc…]
|
[^abc…]
|
匹配除了 “abc... ” 中的任意字符
|
r*
|
r*
|
匹配零個或多個 “r ”
|
r\+
|
r+
|
匹配一個或多個 “r ”
|
r\?
|
r?
|
匹配零個或一個 “r ”
|
r1\|r2
|
r1|r2
|
匹配一個 “r1 ” 或 “r2 ”
|
\(r1\|r2\)
|
(r1|r2)
|
匹配一個 “r1 ” 或 “r2 “ ,並作爲括號內的正則表達式
|
emacs
中的正則表達式基本上是
BRE 但含有 ERE 中的元字符
“+
” 和 “?
” 。因此,在
emacs
中沒必要使用 “\
” 來跳脫它們。
grep(1) 可以使用正則表達式來進行文本搜索。
嘗試下列例子
$ egrep 'GNU.*LICENSE|Yoyodyne' /usr/share/common-licenses/GPL GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE Yoyodyne, Inc., hereby disclaims all copyright interest in the program
對於替換表達式,一些字符有特殊的含義。
對 Perl 的替換字符串, “$n
” 代替了 “\n
” ,而
“&
” 則沒有特殊含義。
嘗試下列例子
$ echo zzz1abc2efg3hij4 | \ sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/=&=/' zzz=1abc2efg3hij4= $ echo zzz1abc2efg3hij4 | \ sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/\2===\1/' zzzefg3hij4===1abc $ echo zzz1abc2efg3hij4 | \ perl -pe 's/(1[a-z]*)[0-9]*(.*)$/$2===$1/' zzzefg3hij4===1abc $ echo zzz1abc2efg3hij4 | \ perl -pe 's/(1[a-z]*)[0-9]*(.*)$/=&=/' zzz=&=
請特別注意這些括號正則表達式的格式,以及這些被匹配的文本如何被替換到不同的文本處理工具中的。
These regular expressions can be used for cursor movements and text replacement actions in some editors too.
The back slash "\
" at the end of line in the shell
commandline escapes newline as a white space character and continues shell
command line input to the next line.
Please read all the related manual pages to learn these commands.
The
ed(1)
command can replace all instances of "FROM_REGEX
" with
"TO_TEXT
" in "file
".
$ ed file <<EOF ,s/FROM_REGEX/TO_TEXT/g w q EOF
The
sed(1)
command can replace all instances of "FROM_REGEX
" with
"TO_TEXT
" in "file
".
$ sed -i -e 's/FROM_REGEX/TO_TEXT/g' file
The
vim(1)
command can replace all instances of "FROM_REGEX
" with
"TO_TEXT
" in "file
" by using
ex(1)
commands.
$ vim '+%s/FROM_REGEX/TO_TEXT/gc' '+w' '+q' file
![]() |
提示 |
---|---|
The " |
Multiple files ("file1
", "file2
", and
"file3
") can be processed with regular expressions
similarly with
vim(1)
or
perl(1).
$ vim '+argdo %s/FROM_REGEX/TO_TEXT/ge|update' '+q' file1 file2 file3
![]() |
提示 |
---|---|
The " |
$ perl -i -p -e 's/FROM_REGEX/TO_TEXT/g;' file1 file2 file3
In the perl(1) example, "-i
" is for the in-place editing
of each target file, and "-p
" is for the implicit loop
over all given files.
![]() |
提示 |
---|---|
Use of argument " |
![]() |
注意 |
---|---|
ed(1) and vim(1) are BRE; perl(1) is ERE. |
Let's consider a text file called "DPL
" in which some
pre-2004 Debian project leader's names and their initiation date are listed
in a space-separated format.
Ian Murdock August 1993 Bruce Perens April 1996 Ian Jackson January 1998 Wichert Akkerman January 1999 Ben Collins April 2001 Bdale Garbee April 2002 Martin Michlmayr March 2003
![]() |
提示 |
---|---|
See "A Brief History of Debian" for the latest Debian leadership history. |
Awk is frequently used to extract data from these types of files.
嘗試下列例子
$ awk '{ print $3 }' <DPL # month started August April January January April April March $ awk '($1=="Ian") { print }' <DPL # DPL called Ian Ian Murdock August 1993 Ian Jackson January 1998 $ awk '($2=="Perens") { print $3,$4 }' <DPL # When Perens started April 1996
Shells such as Bash can be also used to parse this kind of file.
嘗試下列例子
$ while read first last month year; do echo $month done <DPL ... same output as the first Awk example
Here, the read
builtin command uses characters in
"$IFS
" (internal field separators) to split lines into
words.
If you change "$IFS
" to ":
", you can
parse "/etc/passwd
" with shell nicely.
$ oldIFS="$IFS" # save old value $ IFS=':' $ while read user password uid gid rest_of_line; do if [ "$user" = "bozo" ]; then echo "$user's ID is $uid" fi done < /etc/passwd bozo's ID is 1000 $ IFS="$oldIFS" # restore old value
(If Awk is used to do the equivalent, use "FS=':'
" to set
the field separator.)
IFS is also used by the shell to split results of parameter expansion, command substitution, and arithmetic expansion. These do not occur within double or single quoted words. The default value of IFS is <space>, <tab>, and <newline> combined.
Be careful about using this shell IFS tricks. Strange things may happen, when shell interprets some parts of the script as its input.
$ IFS=":," # use ":" and "," as IFS $ echo IFS=$IFS, IFS="$IFS" # echo is a Bash builtin IFS= , IFS=:, $ date -R # just a command output Sat, 23 Aug 2003 08:30:15 +0200 $ echo $(date -R) # sub shell --> input to main shell Sat 23 Aug 2003 08 30 36 +0200 $ unset IFS # reset IFS to the default $ echo $(date -R) Sat, 23 Aug 2003 08:30:50 +0200
The following scripts do nice things as a part of a pipe.
表 1.26. List of script snippets for piping commands
script snippet (type in one line) | effect of command |
---|---|
find /usr -print
|
find all files under "/usr "
|
seq 1 100
|
print 1 to 100 |
| xargs -n 1 <command>
|
run command repeatedly with each item from pipe as its argument |
| xargs -n 1 echo
|
split white-space-separated items from pipe into lines |
| xargs echo
|
merge all lines from pipe into a line |
| grep -e <regex_pattern>
|
extract lines from pipe containing <regex_pattern> |
| grep -v -e <regex_pattern>
|
extract lines from pipe not containing <regex_pattern> |
| cut -d: -f3 -
|
extract third field from pipe separated by ": " (passwd
file etc.)
|
| awk '{ print $3 }'
|
extract third field from pipe separated by whitespaces |
| awk -F'\t' '{ print $3 }'
|
extract third field from pipe separated by tab |
| col -bx
|
remove backspace and expand tabs to spaces |
| expand -
|
expand tabs |
| sort| uniq
|
sort and remove duplicates |
| tr 'A-Z' 'a-z'
|
convert uppercase to lowercase |
| tr -d '\n'
|
concatenate lines into one line |
| tr -d '\r'
|
remove CR |
| sed 's/^/# /'
|
add "# " to the start of each line
|
| sed 's/\.ext//g'
|
remove ".ext "
|
| sed -n -e 2p
|
print the second line |
| head -n 2 -
|
print the first 2 lines |
| tail -n 2 -
|
print the last 2 lines |
A one-line shell script can loop over many files using find(1) and xargs(1) to perform quite complicated tasks. See 第 10.1.5 节 “Idioms for the selection of files” and 第 9.3.9 节 “Repeating a command looping over files”.
When using the shell interactive mode becomes too complicated, please consider to write a shell script (see 第 12.1 节 “Shell 腳本”).