熟練掌握 Linux 終端機的鍵盤符號與快捷鍵,能讓你在撰寫腳本、管理系統時事半功倍。本文整理了最實用、最高頻的操作技巧,助你輕鬆駕馭命令列環境。
Tab 鍵是終端機裡的「自動完成」利器,能大幅減少輸入錯誤與時間。
user 後連按兩下 Tab,列出所有以 user 開頭的命令。usera 後按一下 Tab,自動補齊為 useradd。useradd 後連按兩下 Tab,列出當前目錄下所有檔案與目錄。無論身在何處,cd ~ 都能瞬間帶你回到自己的家目錄。
[root@localhost ~]# cd /
[root@localhost /]# pwd
/
[root@localhost /]# cd ~
[root@localhost ~]# pwd
/root
在命令前加 !,即可從歷史記錄中喚起最近一個以該字串開頭的指令。
[root@localhost ~]# find /root/install.log
[root@localhost ~]# file /root/install.log
[root@localhost ~]# !f # 喚起上一個以 f 開頭的命令 → file /root/install.log
[root@localhost ~]# !fi # 喚起上一個以 fi 開頭的命令 → file /root/install.log
[root@localhost ~]# !fin # 喚起上一個以 fin 開頭的命令 → find /root/install.log
[root@localhost ~]# myhost=www.example.com
[root@localhost ~]# echo $myhost
www.example.com
命令結尾加 &,讓任務在背景默默跑,不佔用終端機。
[root@localhost ~]# while true; do echo hello >> /dev/tty2; sleep 1; done &
[root@localhost ~]# while true; do echo www.example.com >> /dev/tty2; sleep 1; done &
% 代表背景任務的編號(注意:任務 ≠ 進程)。
[root@localhost ~]# [Ctrl]+[Alt]+[F2] # 切換到第二個控制台 /dev/tty2 觀察輸出
# 在 [Ctrl]+[Alt]+[F1] 和 [F2] 之間切換,觀察輸出變化
[root@localhost ~]# jobs # 列出所有背景任務
[root@localhost ~]# fg %1 # 將任務 %1 調回前景執行
[root@localhost ~]# [Ctrl]+z # 暫停當前前台任務
[root@localhost ~]# jobs
[root@localhost ~]# kill %2 # 終止任務 %2
[root@localhost ~]# jobs
[root@localhost ~]# bg %1 # 將暫停的任務 %1 恢復在背景執行
[root@localhost ~]# jobs
`命令`(反引號):執行命令並將輸出結果代入。'字串'(單引號):純字串,不展開變數。"字串"(雙引號):字串,但會展開變數。[root@localhost ~]# echo `hostname` # 執行 hostname 並輸出結果
[root@localhost ~]# echo 'hostname' # 直接輸出字串 hostname
[root@localhost ~]# echo "hostname" # 直接輸出字串 hostname
管道 | 將前一個命令的標準輸出作為下一個命令的標準輸入。
[root@localhost ~]# ls -l /etc | more
[root@localhost ~]# cat /etc/passwd | awk -F: '{print $7}' | sort | uniq
^:匹配字串開頭。$:匹配字串結尾。>:輸出導向(覆蓋寫入)。<:輸入導向。>>:追記(附加到檔案末尾)。[root@localhost ~]# grep ^root < /etc/passwd > result1.txt
[root@localhost ~]# cat result1.txt
[root@localhost ~]# grep bash$ < /etc/passwd > result1.txt
[root@localhost ~]# grep bash$ < /etc/passwd > result2.txt
[root@localhost ~]# cat result1.txt
[root@localhost ~]# cat result2.txt
[root@localhost ~]# grep root < /etc/passwd >> result2.txt
[root@localhost ~]# cat result2.txt
多動手實作,這些技巧很快就會變成你的肌肉記憶,大幅提升 Linux 日常操作效率。