跳轉到內容

Linux 指南/使用 Shell

來自華夏公益教科書

命令列介面 (CLI 或終端) 乍一看可能令人生畏,但重要的是要記住,命令列確實是你的朋友。無數的工具任你使用,可以將原本需要費時費力的工作(例如從長檔案中刪除每行的最後四個字元)變成只需要兩分鐘就能完成的任務。

對於每個 Linux 發行版,命令列提示符看起來都略有不同。例如,在一個系統中,你可能會看到你的使用者名稱、'@' 符號、機器名、當前目錄以及提示符。

       user@linux ~/$ 

這是一個非常常見的提示符。你也可以看到你的使用者名稱,一個空格,計算機的完全限定域名,當前工作目錄的完整路徑,然後是提示符。在上面的示例中,'user' 是使用者名稱,'linux' 是你登入的主機(計算機)的名稱。

       user linux.box.com /home/user$ 

提示符因系統而異,這取決於許多因素。例如,它可能是由你的特定 Linux 發行版的建立者設定的預設配置。它也可能由管理計算機的人員配置。也許你自己配置了想要顯示的提示符的樣子。

配置命令提示符外觀的方式取決於你使用的 Shell,而 Shell 是大多數人通常稱為“命令列”的部分,而實際上它只是一個提供對核心服務的介面的軟體。'Shell' 和 '命令列' 之間的區別僅僅在於 Shell 指的是提供 命令列介面特定軟體(例如 BASH、Tch、ksh 等)。大多數現代 Linux 系統使用 BASH (Bourne Again SHell) 作為預設 Shell。

命令列中使用的命令可能看起來有點神秘,因為它們往往非常短。這是因為 Linux 命令列的根源來自那些單個字母輸入可能需要大量時間才能從終端傳送到中央伺服器,然後再傳回終端並列印到紙捲上的系統。在那些舊的系統中,輸入越短越好,因為這意味著在發出命令和接收輸出時等待的時間越短。記住每個命令代表什麼詞語的最佳方法是找出命令是哪個詞語的縮寫。這對以後記住命令大有幫助。

一些有用的終端命令

[編輯 | 編輯原始碼]

常用命令摘要

[編輯 | 編輯原始碼]
  • ls - 此命令 lists 當前工作目錄的內容。
  • pwd - 顯示你的 present working directory 是什麼。
  • cd - 讓你 change directories。
  • rm - Removes 一個或多個檔案。
  • rmdir - Remove 一個空 directory。
  • mkdir - Make 一個 directory。
  • ps - 提供正在執行的 processes 列表。
  • cp - Copy 一個檔案。
  • mv - Move 一個檔案(這也被用來重新命名檔案,將它從一個檔名“移動”到另一個檔名)。
  • grep - global regular expression print 程式允許你在檔案或另一個程式的輸出中進行搜尋。
  • find - 在檔案系統中查詢檔案
  • man - 顯示大多數命令的手冊(包括 'man')。
提示
有關命令的幫助資訊,請嘗試 man <command>,這將顯示該命令的手冊。請注意,一些命令內建在你的 Shell 中,沒有手冊頁,請使用你的直譯器內部命令(應該是 help <command>)。

使用常用命令

[編輯 | 編輯原始碼]
使用 ls
[編輯 | 編輯原始碼]
       user@linux ~/$ ls
       Afilez  Report.doc  aFilea  finances.xls  myPic.jpg  report1.doc  vacation pictures

你可能會從示例中注意到,'ls' 的預設輸出中的檔案不是嚴格按照字母順序排列的。這是因為輸出是根據每個字母的數字 ASCII 值排序的。因為大寫字母的 ASCII 值比小寫字母的 ASCII 值低,所以返回的結果總是先列出以大寫字母開頭的檔案。例如,如果我們在目錄中新增 AZTRIP 檔案,我們將首先列出 'AZTRIP' 檔案,然後列出 'Afilez' 檔案,因為 'Z' 的 ASCII 值在數字上低於 'f' 的 ASCII 值。

如果你對字母的 ASCII 值感到困惑,這裡需要記住的一點是,大寫字母優先於小寫字母,並將首先出現在列表中。結果是檔案首先按大小寫排序,然後按字母順序排序。

ls 的預設輸出不如它可以顯示的那麼有用。例如,根據示例中的輸出,我們不知道哪些是檔案,哪些是目錄。我們可以推測 "Afilez"、"aFilea" 和 "vacation pictures" 都是目錄,因為它們在檔名之後沒有副檔名。為了確認這一點,我們可以將 'l' 引數傳遞給 'ls' 以獲得“長列表格式”輸出。

       user@linux ~/$ ls -l
       -rw-r--r-- 1 adrong mkgroup-l-d 163328 Jul 24 11:42 AZTRIP
       -rw-r--r-- 1 adrong mkgroup-l-d  11264 Jul 24 11:42 Afilez
       -rw-r--r-- 1 adrong mkgroup-l-d  22528 Jul 24 11:43 Report.doc
       -rw-r--r-- 1 adrong mkgroup-l-d  24576 Jul 24 11:42 aFilea
       -rw-r--r-- 1 adrong mkgroup-l-d 300032 Jul 24 11:43 finances.xls
       -rw-r--r-- 1 adrong mkgroup-l-d  47104 Jul 24 11:41 myPic.jpg
       -rw-r--r-- 1 adrong mkgroup-l-d  17920 Jul 24 11:43 report1.doc
       drwxr-xr-x 1 adrong mkgroup-l-d      0 Jul 24 11:24 vacation pictures

上面的輸出中的第一個字元表示檔案型別;其中,連字元表示檔案,字母 'd' 表示目錄。從這個輸出中,我們可以看到唯一的目錄是 "vacation pictures"

注意
大多數系統對 ls 命令都有別名,以包含 '--color' 標誌,以便命令用不同的顏色突出顯示不同的檔案型別。目錄通常顯示為藍色。如果你的 'ls' 命令的輸出始終是相同顏色,請嘗試 "ls --color"。
提示
ls 命令的另一個常用引數(也稱為“引數”)是 'a',它顯示所有檔案,包括以句點開頭的所有隱藏檔案和資料夾。引數也可以合併成一個字母塊。例如,“ls -l -a”也可以表示為“ls -la”。
使用 cd
[編輯 | 編輯原始碼]

cd 命令允許你在系統中從一個目錄導航到另一個目錄。使用 cd 命令時,你需要知道的第一件事是,與 Windows 不同,Linux 不使用驅動器磁碟機代號的概念。相反,所有內容都在根目錄 '/' 內,包括其他磁碟驅動器。

使用 cd 導航到想要去的目錄有兩種方法。它們被稱為“完整路徑”和“相對路徑”。

完整路徑始終以根目錄 '/' 開頭。例如,如果我們在主目錄 '/home/user' 中,並且想要導航到 'vacation pictures' 目錄,我們將發出以下命令。

       user@linux ~/$ cd /home/user/vacation\ pictures
       user@linux vacation pictures/$ 

您可能會注意到我們的提示略有改變,以指示我們當前所在的目錄。在大多數系統上都是如此,但正如之前所討論的,這取決於您 shell 的配置方式。您可能還會注意到“vacation”和“pictures”之間的反斜槓。此反斜槓稱為“跳脫字元”,它告訴 cd 命令空格是目錄名稱的一部分。如果省略反斜槓,cd 命令將出錯並告訴我們它找不到目錄“vacation”。如果您不喜歡鍵入反斜槓或目錄名稱中有許多空格,您可以在路徑周圍使用引號。

相對路徑可以從多種方式開始,但始終描述如何從您當前所在的目錄獲取特定目錄。為此,我們需要知道如何移動到直接包圍該目錄的目錄。這些目錄是父目錄和子目錄。

子目錄是包含在我們當前所在的目錄中的任何目錄。鑑於下面“ls -l”的輸出,我們看到 chicago、florida 和“new york”都是“vacation pictures”目錄的子目錄。

       user@linux vacation pictures/$ ls -l
       drwxr-xr-x 1 adrong mkgroup-l-d 0 Jul 24 12:44 chicago
       drwxr-xr-x 1 adrong mkgroup-l-d 0 Jul 24 12:44 florida
       drwxr-xr-x 1 adrong mkgroup-l-d 0 Jul 24 12:44 new york

父目錄是包含我們所在資料夾的目錄。這使得“vacation pictures”資料夾成為“chicago”、“florida”和“new york”目錄的父目錄。

要 cd 到子目錄,您可以從路徑名稱開頭使用“./”,這表示我們已經所在的目錄,或者您可以立即從子目錄的名稱開始。例如,以下兩個命令都將您更改為“florida”目錄。

       user@linux vacation pictures/$ cd ./florida
       user@linux florida/$ 
       user@linux vacation pictures/$ cd florida
       user@linux florida/$ 

要 cd 到父目錄,您始終指定“../”。以下命令將返回我們到“vacation pictures”目錄。

       user@linux florida/$ cd ../
       user@linux vacation pictures/$ 

如果我們已經在“chicago”目錄中並且想要 cd 到“new york”,我們必須首先告訴系統我們要向上移動一級到父目錄,然後到“new york”目錄。我們可以透過說“cd ../”然後“cd new\ york”來做到這一點,或者我們可以使用以下命令一步完成。

       user@linux chicago/$ cd "../new york"
       user@linux new york/$ 
注意
請注意,我們如何在路徑周圍使用引號來 cd 到“new york”目錄。我們本可以改為在空格之前使用反斜槓並省略引號以獲得相同的結果。

類似於“./”和“../”,還有“~/”,它表示我們登入的使用者的主目錄。如果我們想在“/usr/lib”目錄中 cd 到“vacation pictures”資料夾,我們可以使用以下任何命令。

       user@linux lib/$ cd ~/vacation\ pictures
       user@linux lib/$ cd "/home/user/vacation pictures"
       user@linux lib/$ cd ../../home/user/vacation\ pictures
提示
在不指定目錄的情況下使用 cd 命令將返回您到您的主目錄。

複製目錄選項

       $cp -frvp /source /destination
        ^   ^^^^    ^        ^
        |   ||||    |        \----------- Path from root is best
        |   ||||    \-------------------- Path to copy from root best
        |   ||||
        |   ||||                          OPTION FLAGS---------------- 
        |   |||\------------------------- Keep permissions
        |   ||\-------------------------- Verbose
        |   |\--------------------------- Recursive files and folders
        |   \---------------------------- Force
        |                                 ----------------------------
        \-------------------------------- Copy command 
cp exam test
-copy file named "exam" to directory named "test"
cp exam .
-copy file named "exam" to current directory (note period at end of command line)


 cp prod/p* reports
   -copy all files beginning with "p" to reports directory
   -can reverse p* to *p for files ending with "p"


將 img 複製到軟盤

dd bs=2x80x18b if=/dev/fd0 of=/tmp/floppy.img


將原始碼複製到製作 img

dd if=/dev/cdrom of=filename.iso
                    ^------^_________ replace with file name



刪除

Remove directory:
       $rm -frv dir/
        ^   ^^^    ^
        |   ||| \---------------------- Remove directory
        |   ||| 
        |   |||                           OPTIONS-------------------- 
        |   ||\-------------------------- Verbose
        |   |\--------------------------- Recursively through all dir 
        |   \---------------------------- Force
        |                                 ---------------------------
        |
        \-------------------------------- Remove command


rm *     <- Delete all files in directory
rm -r    <- Delete directory and contents


Command options for permissions
r = read
w = write
x = execute
X = execute only if user already has execute
s = set user or group id on execution
t = sticky +
u = permission granted to user who owns file
g = permissions granted to group members
o = permissions granted to users other than "u" or "g"




許可權

          format:
                   drwxrwxrwx
                   ^^^^^^^^^^
                   ||||||||||
                   |||||||\\\----------- other users
                   |||||||
                   ||||\\\-------------- group
                   ||||
                   |\\\----------------- owner
                   |
                   \-------------------- directory = "d" (possible: -, b, c, q)


                Octal Method: chmod 
                 permissions
    4 = read                   examples: 7 = 4+2+1  will show "rwx" 
    2 = write                            6 = 4+2    will show "rw-"
    1 = execute                          5 = 4+1    will show "r-x"
              
     
  Usage:  chmod 755 FileName          <--- change file permissions
  Usage:  chmod -R 755 DirectoryName  <--- change directory permissions recursively
  will show permissions "-rwxr-xr-x" 
         Note: first character in permissions show what kind of file
             - = file
             d = directory
    b, c, or q = device files


使用格式

chmod -R ugoa =+- rwx filename
       ^ ^^^^ ^^^ ^^^     ^
       | |||| ||| |||     |
       | |||| ||| |||     \---------- file or directory
       | |||| ||| |||                 -----------------------------------
       | |||| ||| ||\---------------- Execute
       | |||| ||| |\----------------- Write
       | |||| ||| \------------------ Read
       | |||| |||                     -----------------------------------
       | |||| ||\-------------------- Remove
       | |||| |\--------------------- Add
       | |||| \---------------------- assign
       | ||||                         -----------------------------------
       | |||\------------------------ All
       | ||\------------------------- Others
       | |\-------------------------- Group
       | \--------------------------- User
       |                              -----------------------------------
       \----------------------------- Recursively through all directories
                                      -----------------------------------
       Usage: chmod g+w filename

此外,還可以分配三個額外的許可權

   For files:
         u +-= s  : Set UserID, run as if file-owner
         g +-= s  : Set GroupID, run as if file-group
         o +-= t  : Set "sticky bit", keep executable in swap-space - can only be set by root (no longer supported by Linux-kernel)  
   For directories:
         u +-= s  : Set UserID, files in directory inherits directory's ownership
         g +-= s  : Set GroupID, files in directory inherits directory's group
         o +-= t  : Set "sticky bit", limits the ability to remove a file in a world-writeable directory (like /tmp) to the file's owner.


VI / VIM

VI/M 使用兩種模式來處理文字。要處理可用的各種命令,請使用“<esc>”鍵。要插入文字,只需鍵入“i”即可返回文字插入模式。


入門/基礎------------------------

  Start Vi     vi     [From command line]
  Insert mode  i
  Command mode <esc>
  Save doc     :w   
  Quit app     :q
   
        Usage:  :wq  [will save and exit document]
  Navigation------------------------------
  Right        l
  Left         h
  up           k
  Down         j
  ----------------------------------------

對所有進行排序

   :1,$ !sort

替換文字

   :1,$s /and/AND/g
   ^^^^^   ^   ^  ^
   |||||   |   |  |
   |||||   |   |  \----------- Globally
   |||||   |   \-------------- Replace with
   |||||   \------------------ Find
   |||||
   ||||\---------------------- substitute for text
   |||\----------------------- To last line
   ||\------------------------ separator
   |\------------------------- From line "1"
   \-------------------------- ":" operator to start command processing
Useful tid bit to remove EOL characters from DOS file 
[use key sequence "<ctrl v><ctrl m>" together for EOL char]
 :%s/^M$//

Select Ranges
 :1,$   = All lines in file
 :1,.   = All lines from start of file to current (included)
 :.,$   = All lines from current to end of file (inclusive)
 :.-2   = Single line 2 lines before current line
 :10,20 w abc <enter>    = Write lines 10,20 to new file abc
 :r abc       <enter>    = Reads contents of file abc into working file
 :10,20d      <enter>    = Delete block lines 10 ~ 20

檢視行號

 :set number             to disable  :set nonumber

將行寫入新檔案

 :1,10w abc     [puts lines 1~10 into file abc]

將工作檔案從當前檔案更改為檔案 abc [請確保先儲存]

 :e abc

在游標之後將 abc 檔案讀入工作檔案

 :r abc

從提示符執行命令

 :!cmd    [where cmd is could be a bash command]
Example ->    :r !date   [inserts time and date at prompt]

為程式設計源文字突出顯示啟用語法選項

 :syntax enable      To disable = :syntax off


VI Navigation  [escape key = <esc>]
0  [zero] = Move to beginning of line
G         = Go to end of file
5G        = Move to beginning of 5th line
u         = Undo
.         = Repeat last command
x         = Delete character
dd        = Delete line
dw        = Delete word
d$        = Delete from cursor to end of line
$ then J  = Join/append following line with current
$ then a  = Append input at end of line
A         = Append input at end of line [same as above, but one less key stroke]
i         = Insert text at cursor
/         = Bottom of screen type search string and <enter> will move 
                 cursor to first occurrence

從 Bash 提示符工作

        lpr -P //PrintServer/PrinterName "file name"
   
        Other options:
        -#  Number of copies [example "-2" for 2 copies]
        -c  Make copy before print



  lpq -P PrinterName : Displays printer status report
  lprm 4      : Removes job #4 from printer
  pr          : Formats, paginates, prints header
                 OPTIONS
                   -d : forces double spacing
                   -h : Customize header
                   -l : Change number of lines per page | default=66
    
          example: pr customers | lpr  <format and print file "customers">
          example: lprm 1006           <canceled job 1006>
  lpstat -s
    ex: lp -n 2 all files
    ex: lp -n 3 all files -d a3printer
    ex: lpstat -d a3printer

另請參見:CUPS

磁碟系統

[edit | edit source]
磁碟空間使用情況:du -h <dir>
列出在 <dir> 中找到的每個子目錄的總空間使用量估計值,以及估計的總磁碟空間使用量
檔案系統(已掛載)磁碟空間使用情況:df
列出所有已掛載的磁碟以及塊總數、已使用、空閒和邏輯磁碟名稱
df .
僅列出當前正在工作的已掛載磁碟,以塊顯示總計、已使用、空閒。
df -h
以人類可讀的格式列出所有已掛載磁碟的總計、已使用、空閒和邏輯磁碟名稱(KB、MB、GB、TB)。
df -kh
以人類可讀的格式列出所有已掛載磁碟的總計、已使用、空閒和邏輯磁碟名稱(KB、MB、GB、TB)以及已使用的空間百分比(百分比)[-k] 選項。
列出分割槽:fdisk -l <disk>
列出硬碟驅動器上的所有分割槽,例如 fdisk -l /dev/hda
華夏公益教科書