跳轉到內容

LPI Linux 認證/LPIC1 考試 101/GNU & Unix 命令

來自 Wikibooks,開放世界中的開放書籍
LPI logo

章節概述

[編輯 | 編輯原始碼]
  • 1.103.1 在命令列上工作
  • 1.103.2 使用過濾器處理文字流
  • 1.103.3 執行基本檔案管理
  • 1.103.4 使用流、管道和重定向
  • 1.103.5 建立、監控和殺死程序
  • 1.103.6 修改程序執行優先順序
  • 1.103.7 使用正則表示式搜尋文字檔案
  • 1.103.8 使用 VI 執行基本檔案編輯操作
  • Unix 和 Linux

Unix 和 Linux

[編輯 | 編輯原始碼]

Unix 是最初的網際網路作業系統(NFS、TCP/IP、RPC、...)。Linux 是一個 Unix 克隆,由 Linus Torvalds 獨立編寫,並得到了來自全球網路開發人員團隊的幫助。這兩個系統的特性包括:

  • 可移植性、多使用者、多處理
  • 裝置無關的輸入/輸出
  • 共享資源、高效能和高度安全
  • 行命令
  • 圖形使用者介面

Linux 旨在實現 POSIX 相容性,也支援其他標準 API,如 BSD 和 SVR4。Linux 具有您在現代 Unix 中期望的所有功能,包括真正的多工/多使用者、虛擬記憶體、共享庫、按需載入、共享的寫時複製可執行檔案、適當的記憶體管理和 TCP/IP 網路。

越來越多的公司和組織選擇 Linux,因為它具有高效能、低成本和免版稅的許可證。

Unix 和 Linux

[編輯 | 編輯原始碼]

Unix 是最初的網際網路作業系統,編寫於 1970 年,由 AT&T 貝爾實驗室開發。免費分發給政府和大學。不同的實體支援不同的發行版。

  • System V
  • BSD
  • SCO

大多數版本的 Unix 都有版權許可證。

Linux 由 Linus Torvalds 於 1991 年釋出。Linux 許可證的模式來自 GPL 的複製左。Linux 實現了大多數 System V 和 BSD Unix 命令。使用手冊頁確定版本。

登入和登出

[編輯 | 編輯原始碼]

登入會話是訪問 Linux 系統的第一步。您需要登入 ID 和密碼才能開始使用系統。登入 ID root 是超級使用者 ID,擁有所有許可權,通常分配給系統管理員。當登入會話成功時,它將設定一些環境變數並啟動分配給登入 ID 帳戶的 Shell。

登入時設定的變數示例:$HOME、$SHELL、$PATH 等。透過更改檔案 /etc/login.defs,管理員可以為所有使用者自定義一些登入引數和變數。

其中一些示例

UID_MIN 500
UID_MAX 60000
UMASK 022
ENV_PATH /usr/local/bin:/usr/bin:/bin

要登出,請使用 exit 或 logout 命令。

沒有人能看到您的密碼,即使是管理員也不行。要更改使用者或組的密碼,請使用 passwd。

passwd [options]

常用選項

  • -l, -u : 鎖定和解鎖帳戶。
  • -g [| r]: 用於組。
  • -g 設定組密碼,-r 移除密碼。
  • -x|n : 密碼有效期最長和最短天數。

一般來說,密碼必須

  • 具有最小長度
  • 不包含任何英文單詞
  • 包含非字母數字字元
  • 包含大小寫字母的混合。

使用者資訊

[edit | edit source]

每個使用者帳戶在檔案中都有一行定義/etc/passwd. 加密後的密碼儲存在/etc/shadow. 的格式是/etc/passwd

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/bin/bash
daemon:x:2:2:Daemon:/sbin:/bin/bash
yann:x:500:100:Yann Forget:/home/yann:/bin/bash

x 欄位是密碼的舊位置。

的格式是/etc/shadow

root:IMXweyiV816gg:11996:0:10000::::
bin:!*:8902:0:10000::::
daemon:*:8902:0:10000::::
yann:GoIM8j1S.IuTY:11996:0:99999:7:::

加密密碼的 * 表示尚未定義密碼。加密密碼之前的 ! 表示帳戶已鎖定。

組資訊

[edit | edit source]

每個使用者組在檔案中都有一行/etc/group. 加密後的密碼儲存在/etc/gshadow. 的格式是/etc/group

root:x:0:root
bin:x:1:root,bin,daemon
daemon:x:2:
video:x:33:yann

/etc/gshadow 的格式是

root:*:root:root
bin:*:root:root
daemon:*:root:root
video:*:root:root,yann

組密碼很少實現,因為您必須將密碼傳遞給組成員。

其他命令

[edit | edit source]

要獲取有關登入會話的資訊,請使用 id。

id [options] [username]

常用選項:-g : 只打印組 ID。-u : 只打印使用者 ID。

示例

$ id
uid=0(root) gid=0(root) groups=0(root), 1(bin), 14(uucp), 15(shadow),16(dialout)

要使用其他使用者 ID 和組 ID 執行 shell,請使用 su。

su [options] [username]

常用選項:-s : 選擇其他 shell。

示例

$ su toto
passwd:

Shell

[edit | edit source]

Shell 是一個命令列直譯器,

  • 提示輸入命令。
  • 解釋命令,其中可能包括
  • I/O 重定向、管道、檔名生成等。
  • 執行命令。
  • 執行指令碼語言。

有幾個流行的 shell

  • sh: Bourne shell,標準指令碼 shell。
  • csh: Berkeley shell,作業控制、命令歷史記錄、別名。
  • ksh: Korn shell,Bourne 語法,具有 Berkeley 功能。
  • bash: Bourne Again shell,免費的 Korn 類 shell。
  • t csh: 免費的 Berkeley 克隆,具有許多擴充套件。

大多數 shell 允許您自定義提示和環境。對於 bash,提示變數是 PS1。對於 bash,可用於自定義環境的檔案是

  • .bashrc 針對每個新的 bash 會話執行
  • .bash_profile 在登入時執行
  • .bash_logout 在登出時執行

練習

[edit | edit source]

使用過濾器處理文字流

[edit | edit source]

概述

[edit | edit source]

描述:考生應能夠將過濾器應用於文字流。任務包括透過文字實用程式過濾器傳送文字檔案和輸出流以修改輸出,以及使用 GNU textutils 包中找到的標準 UNIX 命令。

關鍵檔案術語實用程式包括
cat
cut
expand
fmt
head
join
nl
od
paste
pr
sed
sort
split
tac
tail
tr
unexpand
uniq
wc

模式匹配和萬用字元

[edit | edit source]

萬用字元是用於檔名的模式匹配機制。萬用字元的目的是提高生產力:找到您不完全記得的檔案。找到具有某些共同點的檔案。使用一組檔案而不是單個檔案。

shell 解釋這些特殊字元

! @ # $ % ^ & * ( ) { } [ ] | \ ; ~ ' " ` ?

用於萬用字元的字元是

?  *  [  ]  ~

如果您使用萬用字元,shell 將嘗試從它們生成一個檔案。嘗試以下操作

echo all files *

特殊萬用字元

? match any one character.
* Any string
[abcfghz] One char set
[a-z] One char in range
[!x-z] Not in set
~ Home directory
~user User home directory

示例

? One character filenames only
[aA]??? Four characters, starting with a or A.
~toto pathname of toto home directory
[!0-9]* All string not starting with a number.

這些命令呢?

ls [a-z][A-Z]??.[uk]
ls big*
ls a???a
ls ??*

Shell 和萬用字元

[edit | edit source]

shell 命令列可以是簡單的命令或更復雜的命令。

ls -l [fF]*
ls *.c | more
ls -l [a-s]* | mail `users`

shell 中的第一件事是解釋萬用字元。只有 shell 解釋未引用的萬用字元。

引用和註釋

[edit | edit source]

引用

[edit | edit source]

引用是為了防止 shell 解釋特殊字元並將多個單詞轉換為一個 shell 單詞。

  • 'string' 引號內的幾乎所有內容都是文字
echo 'He did it, "Why?"'
echo 'Because "#@&^:-)"'
echo '$VAR='Me
  • "string" 與 'string' 相似,但解釋 $、\、 !
echo "What's happening?"
echo "I don't know but check this $ANSWER"
  • 反斜槓 \ 將下一個字元視為文字
echo \$VAR=Me
echo What\'s happening\?
  • 我們如何顯示反斜槓?使用以下行
echo \\

註釋

[edit | edit source]

您可以在命令列或指令碼中添加註釋。使用字元 #。空格必須緊接在 # 之前。

示例

echo $HOME # Print my Home directory
echo "### PASSED ###" # Only this part is a comment
echo The key h#, not g was pressed.

命令

  • cat、tac:連線檔案並列印到標準輸出。
  • head、tail:輸出檔案的開頭和結尾部分。
  • nl:對檔案進行編號。
  • wc:列印檔案中的位元組數、單詞數和行數。
  • cut:從檔案的每一行中刪除部分。
  • tr:轉換或刪除字元。
  • expand、unexpand:將製表符轉換為空格,將空格轉換為製表符。
  • paste:合併檔案中的行。
  • join:根據公共欄位連線兩個檔案中的行。
  • uniq:從排序檔案中刪除重複行。
  • split:將檔案拆分為多個片段。
  • fmt:簡單的最佳文字格式化程式。
  • pr:轉換文字檔案以進行列印。
  • sort:對文字檔案的行進行排序。
  • od:以八進位制和其他格式轉儲檔案。

連線檔案

[edit | edit source]

要連線檔案,請使用 cat。

cat [options] [files...]
tac [options] [files...]

結果顯示在標準輸出中。

常用選項

-s: never more than one single blank line.
-n: number all output line.

示例

cat file  # Display file to the stdout.
cat chapter* # Display all chapters to stdout.
cat -n -s file # Display file with line number with single blank line.

要以相反的順序連線檔案,請使用 tac。

檢視檔案的開頭和結尾

[edit | edit source]

要檢視檔案開頭或結尾的幾行,請使用 head 或 tail。

head [options] [files...]
tail [options] [files...]

結果顯示在標準輸出中。

常用選項

-n: number of lines to be displayed. (head and tail)
-c: number of bytes to be displayed. (head and tail)
-f: append output. (tail)
-s #: iteration for new data every # sec. (tail)

示例

head file # Display the first 10 lines of file.
head -n 2 file # Display the first 2 lines of file.
tail -c 10 file # Display the last 10 bytes of file.
tail -f -s 1 /var/log/messages 
Display the last 10 lines of messages, block and check for new data every second.

對檔案行進行編號

[edit | edit source]

要將行號新增到檔案,請使用 nl。

nl [options] [files...]

結果顯示在標準輸出中。

常用選項

-i #: increment line number by #.
-b: numbering style:
   a: number all lines
   t: non empty line
   n: number no line
-n: numbering format:
   rz: right justified
   ln: left justified.

示例

nl file # Add the line number in each line in the file.
nl -b t -n rz file # Add the line number to each non-empty line with zero-completed format.

統計檔案中的專案

[edit | edit source]

要列印檔案的行數、單詞數和字元數,請使用 wc。

wc [options] [files...]

結果顯示在標準輸出中。

常用選項

-c: the byte size.
-m: the number of character.
-w: the number of word.
-l: the number of line.
-L: length of the longest line.

示例

wc *.[ch] # Display the number of lines, words, and characters for all files .c or .h.
wc -L file # Display the size of the longest line.
wc -w file # Display the number of words.

剪下檔案中的欄位

[edit | edit source]

要從檔案的每一行中刪除部分,請使用 cut。

cut [options] [files...]

結果顯示在標準輸出中。

常用選項

-b #: Extract the byte at position #.
-f #: Extract the field number #.

示例

cut -b 4 file # Extract and display the 4th byte of each line of file. 
cut -b 4,7 file # Extract and display the 4th and 7th byte of each line.
cut -b -2,4-6, 20- file
# Extract character 1 and 2, 4 to 6 and 20 to the end of the line for each line of file.
cut -f 1,3 -d: /etc/passwd # Extract the username and ID of each line in /etc/passwd.

預設分隔符是 TAB,但可以使用 -d 指定。

字元轉換

[edit | edit source]

要將標準輸入轉換為標準輸出,請使用 tr。

tr [options] SET1 SET2

常用選項:-d:刪除 SET1 中的字元。-s:將 SET1 中的字元序列替換為一個。

示例

tr ‘a‘ 'A'  # Translate lower a with A
tr ‘[A-Z]’ ‘[a-z]’ # Translate uppercase to lowercase
tr -d ‘ ‘ # Delete all spaces from file

要將製表符轉換為空格,請使用 expand,要將空格轉換為製表符,請使用 unexpand。

expand  file
unexpand file

行操作

[edit | edit source]

要貼上多個檔案的多行,請使用 paste。

paste [options] [files...]

常用選項

-d #: delimiter: Use # for the delimiter.
-s: serial: paste one file at the time.

示例

paste f1 f2 # Display line of f1 followed by f2.
paste -d: file1 file2 # Use ':' for the delimiter.

要連線多個檔案的多行,請使用 join。

join file1 file2 

要刪除重複行,請使用 uniq。

uniq [options] [files...]

常用選項

-d: only print duplicated lines.
-u: only print unique lines.

示例

uniq -cd file # Display the number of duplicated line.

拆分檔案

要拆分大檔案,請使用 split。

split [options] file

常用選項

-l #: split every # lines.
-b #: split file in bytes or b for 512 bytes, k for 1Kbytes, m for 1 Mbytes.

示例

split -l 25 file  # Split file into 25-line files.
split -b 512 file # Split file into 512-byte files.
split -b 2b file  # Split file into 2*512-byte files.

列印格式

[edit | edit source]

要格式化檔案,請使用 fmt。

fmt [options] [files...]

常用選項:-w #:最大行寬。

示例

$ fmt -w 35 file # Display 35-character lines width.

要格式化印表機的檔案,請使用 pr。

pr [options] [files...]

常用選項:-d:雙倍行距。

示例

$ pr -d file # Format file with double-space.

對文字檔案進行排序

[edit | edit source]

要對檔名中的行進行排序,請使用 sort。

sort [options] file

結果顯示在標準輸出中。

常用選項

-r : Reverse
-f : Ignore case
-n : Numeric
-o file: Redirect output to file
-u : No duplicate records
-t; : Use ';' as delimiter, rather than tab or space.

示例

sort file -r
sort file -ro result

二進位制檔案轉儲

[edit | edit source]

要轉儲二進位制檔案,請使用 od。

od [options] file

結果顯示在標準輸出中,並以八進位制的偏移地址開頭。

常用選項

-c: each byte as character
-x: 2-byte in hex
-d: 2-byte in decimal
-X: 4-byte in hex.
-D: 4-byte in decimal.

示例

$ od -cx /bin/ls
0000000 177   E   L   F 001 001 001  \0  \0  \0  \0  \0  \0  \0  \0  \0
       457f 464c 0101 0001 0000 0000 0000 0000
0000020 002  \0 003  \0 001  \0  \0  \0     224 004  \b   4  \0  \0  \0
       0002 0003 0001 0000 9420 0804 0034 0000
0000040   °   ²  \0  \0  \0  \0  \0  \0   4  \0      \0 006  \0   (  \0
       b2b0 0000 0000 0000 0034 0020 0006 0028
0000060 032  \0 031  \0 006  \0  \0  \0   4  \0  \0  \0   4 200 004  \b
       001a 0019 0006 0000 0034 0000 8034 0804

練習

[edit | edit source]
  1. 使用萬用字元,列出 /etc 目錄中所有包含 'x' 後跟 'in' 的檔名。
  2. 使用萬用字元,列出所有以 'a' 到 'e' 之間的任何字元開頭,至少包含兩個字元,且不以數字結尾的檔名。
  3. 使用萬用字元,列出所有精確包含 4 個字元的檔名,以及所有以大寫字母開頭的檔名。不要進入找到的任何目錄。
  4. 使用萬用字元,列出 /bin 中所有包含 'sh' 的檔案。
  5. 顯示你的環境變數 HOME,前面加上字串 "$HOME value is:"。
  6. 顯示 $SHELL 的內容,前後加上兩個星號字元。
  7. 如何使用雙引號和反斜槓,透過 echo 顯示以下字元字串?
    • @ # $ % ^ & * ( ) ' " \
  8. 編寫 echo 命令來顯示以下兩個字串
    • That's what he said!
    • 'Never Again!' he replied.
  9. 顯示 /etc 目錄中所有以字母 h 開頭的檔案中的單詞數量。
  10. 如何使用兩張 1.44M 軟盤傳送一個 2M 檔案?如何將拆分檔案的各個部分拼合在一起?
  11. 將 /etc/password 中的 : 分隔符轉換為 # 的命令是什麼?

執行基本檔案管理

[edit | edit source]

概述

[edit | edit source]

描述:候選人應該能夠使用基本的 UNIX 命令來複制、移動和刪除檔案和目錄。任務包括高階檔案管理操作,例如遞迴複製多個檔案、遞迴刪除目錄以及移動符合萬用字元模式的檔案。這包括使用簡單和高階萬用字元規範來引用檔案,以及使用 find 來查詢並根據型別、大小或時間對檔案進行操作。

關鍵檔案術語實用程式包括
cp
find
mkdir
mv
ls
rm
rmdir
touch

檔案通配

cp:複製檔案和目錄。ls:列出目錄內容。

建立和刪除目錄

[edit | edit source]

要建立目錄,請使用 mkdir。

mkdir [options] dir

常用選項

-m  mode: set permission mode. Default use umask.
-p  parent: create parent directory as needed.

示例

mkdir -m 0700 bin
mkdir -p bin/system/x86

要刪除空目錄,請使用 rmdir。

rmdir [options] dir

常用選項

-p  parent: remove empty subdirectories.

示例

rmdir  tmp
rmdir -p bin/system/x86

複製檔案和目錄

[edit | edit source]

要將一個檔案複製到另一個檔案或目錄中,請使用 cp。

cp [options] source target

源和目標可以是檔案或目錄。

常用選項

-i  interactive: prompt to overwrite
-r  recursive: copy the subdirectories and contents. Use -R for special files.
-f  force: force the overwriting

預設情況下,將靜默覆蓋目標檔案。不會改變原始檔。

示例

cp *.[a-z] /tmp
cp readme readme.orig
cp  ls /bin
cp -ri bin/* /bin

移動和重新命名檔案

[edit | edit source]

要重新命名檔案或目錄,或將檔案或目錄移動到另一個位置,請使用 mv。

mv [options] source target

源和目標可以是檔案或目錄。

常用選項

-i  interactive: prompt to overwrite
-f  force: force the overwriting
-v verbose

預設情況下,將靜默覆蓋目標檔案。

示例

mv *.[a-z] /tmp
mv readme readme.orig
mv ls /bin
mv -fi bin/* /bin

列出檔名和資訊

[edit | edit source]

列出當前目錄中的檔案的命令是 ls。

ls [options] [filenames]

常見選項是

-l for a long format
-F Append a file type character
-a All files, including hidden
-R Recursive listing of subtree
-d Do not descend into directory

ls 等效於 DOS 上的 dir 命令。

ls 輸出示例

$ ls -l /bin/ls
-rwxr-xr-x    1   root  root  46784 mar 23  2002 /bin/ls
$ ls -ld /bin
drwxr-xr-x    2 root   root   2144 nov  5 11:55 /bin
$ ls -a .
.bash_history .bash_profile .bashrc ...
$ ls -dF /etc .bashrc /bin/ls
.bashrc  /bin/ls*  /etc/

檔案型別

[edit | edit source]

長格式表示

$ ls -l /etc/hosts    #List a long format of the file hosts
-rw-r—r-- 1 root root 677 Jul 5 22:18 /etc/hosts

檔案內容和位置 Linux/Unix 不透過檔名副檔名區分檔案,例如 Windows。要確定檔案內容,請使用 file。

$ file /etc .bashrc /bin/ls /dev/cdrom
/etc:       directory
.bashrc:    ASCII English text
/bin/ls:    ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped
/dev/cdrom: symbolic link to /dev/hdc

要確定命令是內建的 shell 命令還是程式,請使用 type,並使用 which 查詢其位置。

$ type cp cd ls which type
cp is /bin/cp
cd is a shell builtin
ls is aliased to `ls $LS_OPTIONS'
which is aliased to `type -p'
type is a shell builtin
$ which cut
/usr/bin/cut

建立和使用檔名

[edit | edit source]

檔名可以使用以下方法建立

  • I/O 重定向
cat chapter1 chapter2 > book
  • 編輯器,例如 vi。
vi mynewfile
  • 許多 Unix 實用程式
cp file newfile
  • 應用程式
netscape
  • touch 命令,用於建立空檔案(或更新現有檔案的“修改日期”)
touch memo

有效的檔名可以包含

  • 每個檔名最多 255 個字元
  • 區分大小寫 'A' 和 'a' 是不同的
  • 除正斜槓 '/' 之外的任何字元
  • 建議使用字母數字字元以及加號、減號和下劃線字元。
  • 要避免的字元
  • 連字元。
  • touch my-file -lt
  • 空格。
touch more drink
touch "more drink"
  • 大多數其他特殊字元 !@#$%^&*():;"'}{|\<,>.?~`
touch memo*

刪除檔案或目錄

[編輯 | 編輯原始碼]

要刪除檔案或子樹目錄,請使用 rm。

rm [options] files

檔案可以是檔案或目錄。

常用選項

-i  interactive: prompt to for each removal
-f  force: force the overwriting
-r recursive: remove subtree directories and contents

沒有 unremove 或 undelete 命令。

示例

rm *.[a-z]
rm readme readme.orig
rm  ls /bin
rm -rfi /bin
cd; rm -rf *  .* # !! this removes all files of in the home directory of the current user, as well as those in the subdirectories !!

在子樹目錄中查詢檔案

[編輯 | 編輯原始碼]

要搜尋子樹目錄中的檔案,請使用 find。

find [subtrees] [conditions] [actions]

該命令可以接受多個條件,並將在子樹中遞迴搜尋。

一些可能的條件是

-name [FNG] # Search fo the FNG name
-type c  # Type of file [bcdfl]
-size [+-]# # Has a +- size in blocks (c:bytes,k:kilo)
-user [name] # Own by user
-atime [+-]# # Accessed days ago +n means not been accessed for the last n days -n means been accessed the last ndays.
-mtime [+-]# # Modified days ago
-perm nnn # Has permision flags nnn 

一些可能的動作是

-print  # Print the pathname
-exec cmd {} \; # Execute cmd on the file
-ok cmd {} \; # Same as -exec but ask first

示例

find . -name '*.[ch]' -print
find /var /tmp . -size +20 -print
find ~ -type c -name '*sys*' -print
find / -type f -size +2c -exec rm -i {} \;
find / -atime -3 -print
find ~jo ~toto -user chloe -exec mv {} /tmp \;

要查詢二進位制檔案、原始檔或手冊頁,請使用 whereis。

Whereis [options]

常用選項

-b: Search only for binaries.
-m: Search only for manual sections.
-s: Search only for sources.

示例

$ whereis host
host: /usr/bin/host /etc/host.conf /usr/share/man/man1/host.1.gz
$ whereis -m host
host: /usr/share/man/man1/host.1.gz

要查詢由 PATH 變數定義的位置的檔案,請使用 which。

$ which -a ls
/bin/ls

-a 將查詢 PATH 中所有可能的匹配項,而不僅僅是第一個匹配項。

  1. 編寫一個互動式命令,刪除您主目錄中的所有 .tmp 檔案。對每個提示都回復 y。
  2. 列出所有使用者主目錄中以 .pdf 結尾、大小超過 50 個塊且自上次訪問已超過一個月的檔案。
  3. 建立一個名為 file.h 的檔案,其中包含在 /usr 目錄中找到的所有以 .h 結尾的檔名。
  4. 對 /usr/src/packages 目錄中找到的所有 c 檔案進行 touch 操作。
  5. 建立新檔案和新目錄時的預設許可權是什麼?
  6. 如何建立檔名中包含空格的新檔案或目錄?(例如:'new dir')
  7. 刪除您主目錄中所有型別為字元和塊的檔案的命令是什麼?
  8. 如何查詢 find 程式的位置?
  9. 刪除 /tmp 中所有不屬於 root 且自上次訪問已超過一週的檔案。

使用流、管道和重定向

[編輯 | 編輯原始碼]

描述:候選人應該能夠重定向流並將它們連線起來,以便高效地處理文字資料。任務包括重定向標準輸入、標準輸出和標準錯誤,將一個命令的輸出傳遞給另一個命令的輸入,使用一個命令的輸出作為另一個命令的引數,以及將輸出傳送到標準輸出和檔案。

關鍵檔案術語實用程式包括
tee
xargs
<
<<
>
>>
|
` `

標準輸入和標準輸出

[編輯 | 編輯原始碼]

對於在終端中執行的每個命令,都有:標準輸入值 0(預設鍵盤)、標準輸出值 1(預設終端)和標準錯誤輸出值 2(預設終端)。

每個通道也可以透過地址標識:&0 表示輸入,&1 表示輸出,&2 表示錯誤。

每個通道 [n] 都可以重定向。[n]< 檔案:n 的預設值為 0,它從檔案讀取標準輸入。[n]> 檔案:預設值為 1,它將標準輸出傳送到檔案,如果檔案存在則覆蓋檔案。(覆蓋)[n]>>檔案:預設值為 1,它將標準輸出追加到檔案。<<詞:讀取標準輸入,直到遇到詞為止。`命令`:用結果替換命令名。

示例

$ pwd > file  # out=file in=none error=terminal.
cat chap* >book # out=book in=none error=terminal.
mv /etc/* . 2>error # out=terminal in=none error=error.
echo end of file >> book # out=book in=none error=terminal.
set -o noclobber # Shell does not clobber existing files.
ls > list 2>&1 # ls and errors are redirected to list.
ls 2>&1 > list # Errors are redirected to standard output and ls output is redirected to list.
cat `ls /etc/*.conf` > conffile 2>>/tmp/errors

將 /etc 目錄中的所有配置檔案連線到 conffile 中,並將錯誤追加到檔案 /tmp/errors 中。

使用管道重定向

管道是同時應用多個命令的有效方法。

command1 | command2

命令 1 的標準輸出將被管道傳輸到命令 2 的標準輸入。標準錯誤不會被管道傳輸。

示例

ls -l /dev | more
ls -l /etc/*.conf | grep user | grep 500
ls -l /bin | mail `users`

要將標準輸出同時重定向到檔案和終端,請使用 tee。

ls -l /dev | tee file
ls -l /etc | tee -a file # Append to the file

構建引數

xargs 實用程式使用標準輸入構建命令的引數列表。

xargs [options] [command]

xargs 命令從標準輸入建立命令的引數列表。它通常與管道一起使用。

常用選項:-p:在執行每個命令之前提示使用者。

示例

ls f* | xargs cat # Print to standard output the content of all files starting with f.
find ~ -name 'proj1*' print | xargs cat

在 Home 目錄中搜索以 proj1 開頭的檔案,並將它們傳送到 cat 的標準輸入。

使用 /dev/null 裝置檔案丟棄輸出或錯誤訊息。

嘗試以下操作

grep try /etc/*
grep try /etc/* 2> /dev/null
grep try /etc/* > /dev/null 2> /dev/null
  1. 建立一個名為 list.bin 的檔案,其中包含 /bin 目錄中的所有檔名。
  2. 編寫一個命令,將 /usr/local/bin 中的檔案列表追加到名為 list.bin 的檔案中,並丟棄所有錯誤輸出。
  3. 將 list.bin 檔案拆分為 50 行長的檔案,並刪除 list.bin。
  4. 從拆分的檔案中重新建立 list.bin,但以反向順序。
  5. 簡化以下命令
ls *.c | xargs rm
ls [aA]* | xargs cat
cat `ls *.v` 2>/dev/null
  1. 使用 find 執行以下命令
more `ls *.c`
  1. 編寫一個命令,建立一個名為 list.sbin 的檔案,其中包含 /sbin 的內容,同時將內容顯示到標準輸出。
  2. 建立一個檔案,在檔名中包含建立時間。
  3. 建立一個檔案,其中包含 /etc 目錄中以 .conf 結尾的所有檔名,以反向順序排列。

建立、監控和殺死程序

[編輯 | 編輯原始碼]

描述:候選人應該能夠管理程序。這包括瞭解如何在前臺和後臺執行作業,將後臺作業移到前臺,反之亦然,啟動一個在沒有連線到終端的情況下執行的程序,以及向程式傳送訊號以在登出後繼續執行。任務還包括監控活動程序,選擇和排序要顯示的程序,向程序傳送訊號,殺死程序,以及識別和殺死在 X 會話關閉後未終止的 X 應用程式。

關鍵檔案術語實用程式包括
&
bg
fg
jobs
kill
nohup
ps
top

建立程序

[編輯 | 編輯原始碼]

正在執行的應用程式是一個程序。每個程序都有:程序 ID。父程序 ID。當前目錄 PWD。檔案描述符表。正在執行的程式。環境變數,從其父程序繼承而來。標準輸入、標準輸出和標準錯誤 其他

Bash 是一個程式,當它被執行時就會變成一個程序。每次您在 shell 中執行命令時,都會建立一個新程序。除了 shell 內建命令。它們在 shell 上下文中執行。使用 type 檢查命令是否為 shell 內建命令。

例如 type cp ls which type 監控程序 系統啟動並執行後,從終端可以使用 ps 程式檢視哪些程序正在執行。要顯示系統中所有程序的詳細資訊,請執行

ps -Al
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
004 S     0     1     0  0  80   0 -   112 do_sel ?        00:00:04 init
004 S     0   381     1  0  80   0 -   332 do_sel ?        00:00:00 dhcpcd
006 S     0  1000     1  0  80   0 -   339 do_sel ?        00:00:00 inetd
044 R     0  1524  1222  0  79   0 -   761 -      pts/3    00:00:00 ps

ps 程式將顯示所有正在執行的程序及其 PID 號和其他資訊。要檢視您登入會話中的程序詳細資訊,請執行

ps -l
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
000 S   500  1154  1139  0  80   0 -   724 wait4  pts/1    00:00:00 bash
002 S   500  1285  1283  0  77   0 - 24432 wait_f pts/1    00:00:00 soffice.bin
040 R   500  1442  1435  0  79   0 -   768 -      pts/4    00:00:00 ps
F: Process Flags 002: being created, 040: forked but didn't exec, 400: killed by a signal.
S: Process States: R: runnable, S: sleeping, Z: zompbie
UID: User ID, PID: Process ID, PPID: Parent Process ID, C: Scheduler, PRI: priority
NI: Nice value, SZ: size of routine, WCHAN: name of routine

監控程序

[編輯 | 編輯原始碼]

要即時監控程序,請使用 top。top

 9:20am  up  2:48,  4 users,  load average: 0.15, 0.13, 0.09

78 個程序:75 個睡眠,3 個執行,0 個殭屍,0 個停止 CPU 狀態:15.3% 使用者,0.3% 系統,0.0% 優先順序,84.2% 空閒 記憶體:254896K 可用,251204K 使用,3692K 空閒,0K 共享,27384K 緩衝 交換:514072K 可用,0K 使用,514072K 空閒 120488K 快取

 PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
1517 rarrigon   0   0 40816  39M 17372 R    15.0 16.0   2:59 mozilla-bin
1727 rarrigon  19   0   988  988   768 R     0.3  0.3   0:00 top
   1 root      20   0   220  220   188 S     0.0  0.0   0:04 init
   2 root      20   0     0    0     0 SW    0.0  0.0   0:00 keventd

RSS:任務使用的物理記憶體總量。SHARE:任務使用的共享記憶體量。%CPU:任務佔用的 CPU 時間比例。%MEM:任務佔用的物理記憶體比例。一旦 top 執行,也可以執行互動式命令:鍵入 N 按 pid 對任務進行排序。鍵入 A 按年齡對任務進行排序(最新的排在最前面)。鍵入 P 按 CPU 使用率對任務進行排序。鍵入 M 按記憶體使用率對任務進行排序。鍵入 k 殺死程序(提示輸入 pid)。

殺死程序

[編輯 | 編輯原始碼]

ps 程式會顯示所有正在執行的程序及其 PID 號碼。一旦知道 PID,就可以向程序傳送訊號。SIGSTOP 停止程序。SIGCONT 繼續已停止的程序。SIGKILL 殺死程序。

用於向程序傳送訊號的程式稱為 kill。

kill -SIGKILL [pid]
kill -63 [pid]
kill -l

預設情況下,程序在前景啟動,並且它是唯一接收鍵盤輸入的程序。使用 CTRL+Z 暫停它。

要在後臺啟動程序,請使用 &。

bash &
xeyes &

作業控制

在 bash 程序中,可以啟動多個作業。用於操作作業的命令是

jobs   # List all the active jobs
bg %job  # Resume job in background
fg %job  # Resume job in foreground
kill %job # Kill background job

當 bash 終止時,從該會話啟動的所有程序都將收到 SIGHUP 訊號。預設情況下,這將終止程序。

要防止程序終止,可以使用 nohup 命令啟動程式。

nohup mydaemon

修改程序執行優先順序

[編輯 | 編輯原始碼]

描述:考生應該能夠管理程序執行優先順序。任務包括以較高或較低優先順序執行程式,確定程序的優先順序以及更改正在執行程序的優先順序。

關鍵檔案術語實用程式包括
nice
ps
renice
top

優先順序

[編輯 | 編輯原始碼]

要以調整後的優先順序啟動命令,請使用 nice。
nice -n +2 [command]
nice -n -19 [command]
nice 程式更改排程器的基本時間量子。
即它告知排程器程序的重要性,這被用作排程器分配多少 CPU 時間的參考。

例如,如果您想在燒錄另一張 CD 時聽音樂,您可以使用 nice -n +5 oggenc,您不應在音樂回放中遇到任何“跳躍”,因為排程器“知道”oggenc 程序不太重要。

該值可以從 -19(最高優先順序)到 +20(最低優先順序)。
預設值為 0。只有 root 可以設定低於零的值。

要修改正在執行的程式的優先順序,請使用 renice。
renice +1 -u root
# 更改所有 root 程序的優先順序。
renice +2 -p 193
# 更改 PID 為 193 的程序的優先順序

  1. 哪些使用者和 root 程序使用最多的記憶體?
  2. 開啟兩個終端。在一個終端中鍵入以下內容
while [ 1 ]
do
echo -n The date is:;
date;
done

從另一個終端中看到您可以停止和繼續列印輸出。

3) 與 2) 相同的開始,但讓列印輸出每隔 3 秒停止 1 秒繼續重複進行。 4) 建立一個 shell 指令碼,將所有名為 apache 的程序的優先順序調整為 19。 5) 從 ps 列印格式為:“使用者名稱”,“命令”,“優先順序” 6) 殺死所有名為“bash”且由使用者 polto 擁有的程序。

正則表示式

[編輯 | 編輯原始碼]

描述:考生應該能夠使用正則表示式操作檔案和文字資料。本目標包括建立包含多個符號元素的簡單正則表示式。它還包括使用正則表示式工具在檔案系統或檔案內容中執行搜尋。

關鍵檔案術語實用程式包括
grep
regexp
sed

模式匹配

[編輯 | 編輯原始碼]

有兩種模式匹配

  • 萬用字元(檔名生成)
  • Regexp(正則表示式)

萬用字元主要應用於在當前目錄或子目錄中使用時。當萬用字元 *, ?, [ - ], ~, 和 ! 在 regexp 中使用時,它們不再生成檔名。

使用 regexp 的一些實用程式是

  • grep, egrep
  • vi
  • more
  • sed
  • Perl

有限的 regexp 搜尋模式 所有使用 regexp 的實用程式都使用它。

  • 任何 1 個字元 . Ab.a Abla 或 Abca
  • 1 個字元集 [ ] Ab[sd]a Absa 或 Abda 僅此而已
  • 1 個字元範圍 [ - ] Ab[a-z]a Abaa 或 Abba 或 ...
  • 不在集合中 [^ ] Ab[^0-9]a Abaa 或 Abba 或 ...
  • 0 個或多個 * Ab*a Absala 或 Aba 或 ...
  • 行開頭 ^ ^Aba 行開頭 > Aba
  • 行結尾 $ Aba$ Aba < 行結尾
  • 字面值 \ Aba\$ Aba$

示例

Ab[0-3]s
^Ab\^bA
[01]bin$
^..\\
[^zZ]oro

有限 regexp 的組合 所有使用 regexp 的實用程式都使用的組合。

  • 任何字串 .* Ab.*a Abrahma 或 Abaa 或 ...
  • 從 [ ]* th[aersti]* 開始的字串 There 或 This 或 ...
  • 多範圍 [ - - ] Ab[0-2][a-c]a Ab0aa 或 Ab1aa 或 ...
  • 匹配 \ \\ \\[a-zA-Z]* \Bethoven

示例

Ab[0-3][a-z]s
...$
^[01]\^2
[0-9][a-z] \$
[a-zA-Z]*
^[^c-zC-Z]*
^[a-zA-Z0-9]$

修飾符模式 替換與 regexp 模式匹配的字串

  • 匹配 m \{m\} b[0-9]\{3\} b911
  • 一個或多個 \{m,\} b[0-9]\{2,\} b52
  • 最多 n \{m,n\} b[0-9]\{2,4\} b1234
  • 單詞開頭 \< \<wh where
  • 單詞結尾 \> [0-9]\> bin01

要查詢檔案中的文字,請使用 grep。

grep [options] [string] [files]

最好引用字串以防止解釋。

常用選項:-i:忽略大小寫 -l:僅列出檔名,如果至少有一個匹配 -c:僅顯示匹配行的數量 -n:也顯示行號 -v:不能匹配。

示例

grep host /etc/*.conf
grep -l '\<mai' /usr/include/*.h
grep -n toto /etc/group
grep -vc root /etc/passwd
grep '^user' /etc/passwd
grep '[rR].*' /etc/passwd
grep '\<[rR].*' /etc/passwd

要對流應用命令,請使用 sed。

sed [address1][,address2][!]command[options] [files...]

sed 程式將在檔案中的地址 1 到地址 2 之間應用命令。地址 1 和地址 2 格式是正則表示式。sed 程式是非互動式編輯工具。

示例

sed '1,3s/aa/bb/g' file # Replace in file from line 1 to 3 aa by bb.
sed '/here/,$d' file # Delete line from here to the end.
sed '/here/d' file # Delete lines with word here.
sed '1,/xxx/p' file # Print lines from 1 to xxx.
sed '/ll/,/ff/!s/maison/house/g' file # In file replace words maison by house excluding lines from ll to ff.
  1. 處理您的 bookmarks.html 檔案以生成一個只包含網站標題的列表,並將列表寫入名為 mywebsites.txt 的檔案。
  2. 將 /etc 中的所有檔案複製到您的 home 目錄中的 etc/。透過將單詞 host 替換為 machine 來顯示所有 *.conf 檔案的內容。
  3. 顯示所有不包含 root 詞語的 *.conf 檔案的內容。使用 grep 和 sed 的命令是什麼?
  4. 列印 root 所屬的所有組名。
  5. 列出所有長度為 4 或 5 個字元的組名。
  6. 列出所有包含不含空格(空白)的字元行的檔案。
  7. 列出 etc/ 目錄中所有包含數字字元的檔案。
  8. 使用 ls 僅列印 / 中的目錄名。
  9. 執行“ps -aux”並將使用者 r_polto 替換為 root,並將結果列印到名為 new_process.txt 的檔案中。
  10. 列出所有名為 apache 且由以“p”或“P”開頭的使用者名稱擁有的程序。

使用 vi 執行基本檔案編輯

[編輯 | 編輯原始碼]

描述:考生應該能夠使用 vi 編輯文字檔案。本目標包括 vi 導航、基本 vi 節點、插入、編輯、刪除、複製和查詢文字。

關鍵檔案術語實用程式包括
vi
/, ?
h,j,k,l
G, H, L
i, c, d, dd, p, o, a
ZZ, :w!, :q!, :e!
:!

在使用 X-Windows 時,您可以使用滑鼠導向的編輯器,例如 xedit。在交叉開發環境中,使用者可以使用自己喜歡的編輯器。在非視窗系統上,您只需要一個鍵盤編輯器,例如 vi。Linux 上的 vi 編輯器與任何 Unix 系統上的 vi 編輯器相同。vi 有兩種模式。

  • 命令模式:您輸入的任何內容都將被解釋為命令
  • 輸入模式:您輸入的任何內容都將插入到檔案中

從一種模式切換到另一種模式 命令模式到輸入模式:i、I、a、A、o、O 鍵 輸入模式到命令模式:ESC 鍵 預設的起始模式是命令模式 可以在您的 HOME 目錄中建立檔案配置 .exrc 來設定一些 vi 的行為。

set ignorecase # No case-sensitive
set tabs=3 # 3 space for tab character

使用 vi 執行基本檔案編輯

進入輸入模式

  • i 在游標前
  • I 在行首
  • a 在游標後
  • A 在行尾
  • o 在下方開啟一行
  • O 在上方開啟一行

刪除

  • dw 刪除單詞
  • dd 刪除行
  • D 刪除到行尾
  • x 刪除游標處的字元

移動游標

  • l 右移一個空格
  • h 左移一個空格
  • j 下移一行
  • k 上移一行
  • $ 行尾
  • ^ 行首
  • w 下一個單詞
  • e 單詞結尾

練習

[edit | edit source]
  1. 使用vi從任何目錄開始編輯一個空的緩衝區。
  2. 在這個緩衝區中輸入幾行文字。
  3. 將緩衝區的內容儲存到目錄中。
  4. 使用vi.
  5. 再次開啟檔案。建立新的一行在您之前輸入的內容下方。(不要使用i從命令模式!)
  6. 退出vi不儲存這些更改。
華夏公益教科書