Linux 是伺服器領域的霸主,也是現代 DevOps 工程師的必備技能。本文整理 150 個最常用的 Linux 指令,從基礎操作到進階技巧,幫助你快速上手 CLI。

1. 文件與目錄操作 (File & Directory)

這些指令用於日常的文件與目錄管理:

指令 說明 常用用法
ls 列出目錄內容 ls -lals -lhls --color
cd 切換工作目錄 cd /var/logcd ~cd ..
pwd 顯示當前目錄絕對路徑 pwd -P (解析符號連結)
cp 複製檔案或目錄 cp a bcp -r dir1 dir2cp -a src/ dest/
mv 移動/重新命名檔案 mv old newmv file ~/dir/
rm 刪除檔案或目錄 rm filerm -rf dirrm -i file
touch 建立空檔案或更新時間戳 touch new.txttouch -t 202401011200 file
mkdir 建立目錄 mkdir projectmkdir -p a/b/c
rmdir 刪除空目錄 rmdir empty_dir
find 搜尋檔案 find . -name "*.txt"find / -mtime -1
ln 建立連結 ln -s target link (軟連結)、ln target link (硬連結)
tree 以樹狀圖顯示目錄結構 tree -L 2tree -a

2. 文件內容查看 (Viewing Content)

指令 說明 常用用法
cat 顯示/串接檔案內容 cat filecat -n filecat a b > c
head 顯示檔案開頭 head -n 10head -f access.log
tail 顯示檔案結尾 tail -n 10tail -f access.log
less 分頁式檢視器 less fileless -N (顯示行號)
more 簡易分頁檢視器 more file
nl 顯示行號 nl filenl -ba file
wc 計算行數/字數/位元組 wc -l filewc -w filewc -c file
od 以二進位格式顯示檔案 od -c fileod -x file
xxd 十六進位檔案查看器 xxd filexxd -r (反向轉換)
file 偵測檔案類型 file script.shfile --mime-type f

3. 文本處理 (Text Processing)

指令 說明 常用用法
grep 全域搜尋正則式 grep pattern filegrep -r "text"grep -i patterngrep -v pattern
egrep 延伸正則搜尋 egrep "pattern1|pattern2"
fgrep 固定字串搜尋 fgrep "literal string"
rg ripgrep (快速搜尋) rg "pattern" -t pyrg --files | head
sed 流式編輯器 sed 's/old/new/g' filesed -i '1d' filesed -n '5,10p'
awk 列式文字處理 awk '{print $1}'awk -F: '/root/ {print $7}' /etc/passwd
cut 切分字串 cut -d: -f1 /etc/passwdcut -c1-5 file
sort 排序 sort filesort -r filesort -n filesort -k2 file
uniq 去重排序列 uniq filesort file | uniq -cuniq -d file
tr 字符轉換 echo "HELLO" | tr 'A-Z' 'a-z'tr -d ' '
diff 比較檔案差異 diff a bdiff -u a bdiff -r dir1 dir2
tee 同時輸出到螢幕和檔案 command | tee output.txttee -a file (追加)
fold 折行文字 fold -w 80 filefold -s (以空格折行)
column 格式化顯示表格 column -t filecolumn -s: -t /etc/passwd
paste 合併行為表格 paste file1 file2paste -s file
fmt 格式化段落 fmt -w 72 filefmt -s file
rev 反轉每行字元 echo "hello" | rev
cut 切分字串 cut -d' ' -f1 file
basename 取得路徑最後部分 basename /path/to/file.txt
dirname 取得路徑目錄部分 dirname /path/to/file.txt

4. 壓縮與解壓 (Compression)

指令 說明 常用用法
tar 打包與解壓縮 tar -czf file.tar.gz dirtar -xzf file.tar.gztar -cjf file.tar.bz2 dir
gzip gzip 壓縮 gzip filegzip -d file.gzgzip -k file (保留原檔)
gunzip 解壓 gzip gunzip file.gz
zcat 查看 gzip 檔不解壓 zcat file.gz
bzip2 BZip2 壓縮 bzip2 filebzip2 -d file.bz2bzip2 -k file
zip 建立 zip 壓縮 zip -r file.zip dirzip -e file.zip file (加密)
unzip 解壓 zip unzip file.zipunzip -l file.zip (僅列出)
xz XZ 壓縮 xz filexz -d file.xzxz -k file
7z 7-Zip 壓縮 7z a file.7z dir7z x file.7z
zstd Zstandard 壓縮 zstd filezstd -d file.zstzstd -19 file (最高壓縮率)

5. 系統資訊 (System Info)

指令 說明 常用用法
uname 顯示系統資訊 uname -auname -r (核心版本)
hostname 顯示/設定主機名 hostnamehostname -I (IP 位址)
uptime 顯示系統運行時間 uptimeuptime -p (易讀格式)
date 顯示/設定日期時間 datedate +%Y%m%ddate -u (UTC)
uptime 系統運行時間 uptimeuptime -p
free 顯示記憶體使用情況 free -h (易讀格式)、free -m (MB)
df 顯示磁碟空間 df -hdf -i (inode 使用)
du 顯示目錄檔案大小 du -sh dirdu -sh *du --max-depth=1
top 動態顯示進程資訊 toptop -p PIDtop -n 1
htop 互動式進程查看器 htophtop PID
ps 顯示進程狀態 ps auxps -efps -ef | grep nginx
who 顯示已登入用戶 whowhoamiwho am i
w 顯示用戶與進程資訊 w
id 顯示用戶與群組 ID idid username
nproc 顯示可用 CPU 核心數 nproc
lscpu 顯示 CPU 詳細資訊 lscpu
lsblk 列出磁碟設備 lsblklsblk -f (顯示檔案系統)
lspci 列出 PCI 裝置 lspcilspci -v
lsusb 列出 USB 裝置 lsusblsusb -v
dmesg 顯示核心日誌 dmesgdmesg | taildmesg | grep -i usb

6. 進程管理 (Process Management)

指令 說明 常用用法
ps 顯示進程資訊 ps auxps -efps -e -o pid,comm
kill 發送信號給進程 kill PIDkill -9 PIDkill -15 PID
pkill 依名稱殺進程 pkill nginxpkill -f patternpkill -u username
killall 殺所有同名進程 killall nginxkillall -9 nginx
nohup 跳離終端執行 nohup command &nohup command > log.txt 2>&1 &
bg 將進程放到背景 bgbg %1
fg 將進程 bring 到前台 fgfg %1
jobs 列出工作 jobs -l
top 動態進程監視器 toptop -p PIDtop -n 1 -b (批次模式)
htop 互動式進程查看器 htophtop -p PID
pgrep 搜尋進程 ID pgrep nginxpgrep -u rootpgrep -f "pattern"
pstree 樹狀顯示進程 pstreepstree PIDpstree -p
nice 設定執行優先級 nice -n 19 commandnice -n -5 command
renice 改變已執行進程優先級 renice +5 PIDrenice -10 PID
strace 追踪系統呼叫 strace commandstrace -p PIDstrace -e trace=open
lsof 列出開啟檔案的進程 lsof -i :80lsof -u userlsof /path/to/file
fuser 找出使用檔案/目錄的進程 fuser filefuser -k file (殺掉進程)
pidof 找出程序名稱的 PID pidof nginxpidof -s nginx (單一 PID)

7. 磁碟與文件系統 (Disk & Filesystem)

指令 說明 常用用法
df 磁碟空間使用情況 df -hdf -idf -hT
du 目錄/檔案大小 du -sh dirdu -sh *du --max-depth=1
mount 掛載文件系統 mount /dev/sda1 /mntmount | columnmount -a
umount 卸載文件系統 umount /mntumount /dev/sda1umount -l /mnt (懶卸載)
fdisk 分割硬碟 fdisk -lfdisk /dev/sda
cfdisk 互動式磁碟分割 cfdisk /dev/sda
mkfs 建立文件系統 mkfs.ext4 /dev/sda1mkfs.vfat /dev/sdb1
fsck 檢查/修復文件系統 fsck /dev/sda1fsck -y /dev/sda1 (自動修復)
blkid 顯示磁碟設備 UUID blkidblkid /dev/sda1
lsblk 列出磁碟設備 lsblklsblk -flsblk -t
fdisk 磁碟分割工具 fdisk -lfdisk /dev/sda
partprobe 重新載入分割表 partprobe /dev/sda
sync 同步緩衝資料到磁碟 sync
mountpoint 檢查掛載點 mountpoint /mnt/disk
findmnt 查找/列出掛載資訊 findmntfindmnt /dev/sda1

8. 網路 (Network)

指令 說明 常用用法
ip 新一代網路配置工具 ip addrip linkip routeip neigh
ifconfig 舊版網路配置 (已棄用) ifconfigifconfig eth0
ping 測試網路連通性 ping google.comping -c 4 google.comping -i 0.5
curl 資料傳輸 (HTTP/FTP/等) curl urlcurl -O urlcurl -X POST -d "data" urlcurl -H "Header: value"
wget 下載網路檔案 wget urlwget -O file urlwget -c url (斷點續傳)
netstat 顯示網路連線 netstat -tlnpnetstat -an | grep :80
ss 新版網路連線查看器 ss -tlnpss -tulnpss -t state established
dig DNS 查詢 dig example.comdig -x 8.8.8.8dig MX example.com
nslookup DNS 查詢工具 nslookup example.comnslookup -type=MX example.com
nslookup DNS 反向查詢 nslookup -type=mx example.comnslookup -type=any example.com
traceroute 追踪路由 traceroute google.comtraceroute -n
tracepath 追踪路由 (無需 root) tracepath google.com
ssh 安全 shell 遠端連線 ssh user@hostssh -p 2222 hostssh -i key.pem host
scp 安全複製遠端檔案 scp local remote:scp remote:/file localscp -r dir remote:
rsync 遠端同步 rsync -av src/ dest/rsync -av --delete src/ dest/rsync -avz --progress
nc Netcat 網路工具 nc -l 8080echo "hi" | nc host 80nc -zv host 80 (端口掃描)
telnet Telnet 測試連線 telnet host port
iptables 防火牆設定 iptables -Liptables -A INPUT -p tcp --dport 80 -j ACCEPT
hostname 顯示/設定主機名 hostnamehostname -I
route 顯示/設定路由表 route -nroute add default gw 192.168.1.1

9. 包管理 (Package Management)

指令 說明 常用用法
apt Debian/Ubuntu 包管理 apt updateapt upgradeapt install pkgapt remove pkgapt search pkgapt list --installed
apt-get apt 的舊版 CLI apt-get install pkgapt-get update
yum RHEL/CentOS 包管理 yum install pkgyum updateyum remove pkgyum list installedyum search pkg
dnf yum 的下一代 (Fedora) dnf install pkgdnf updatednf remove pkg
pacman Arch Linux 包管理 pacman -Syupacman -S pkgpacman -R pkgpacman -Qs pkg
zypper SUSE/openSUSE 包管理 zypper install pkgzypper updatezypper search pkg
npm Node.js 包管理 npm installnpm install pkg -gnpm updatenpm uninstall pkgnpm list -g
pip Python 包管理 pip install pkgpip uninstall pkgpip listpip freeze > requirements.txtpip install -r requirements.txt
snap Ubuntu Snap 包管理 snap install pkgsnap listsnap remove pkgsnap refresh
brew macOS Homebrew brew install pkgbrew upgradebrew listbrew uninstall pkgbrew search pkg
rpm RHEL 套件管理 (底層) rpm -qarpm -ivh pkg.rpmrpm -e pkg
dpkg Debian 套件管理 (底層) dpkg -ldpkg -i pkg.debdpkg -r pkgdpkg -L pkg

10. 用戶與群組 (Users & Groups)

指令 說明 常用用法
useradd 建立新用戶 useradd usernameuseradd -m username (建立家目錄)、useradd -M username (不建立家目錄)
usermod 修改用戶設定 usermod -aG group userusermod -s /bin/bash user (更改 shell)、usermod -L user (鎖定)
userdel 刪除用戶 userdel usernameuserdel -r username (刪除家目錄)
passwd 修改密碼 passwd (修改自己的)、passwd username (root 修改他人)、passwd -d username (清空)
adduser 新增用戶 (Debian 友好版) adduser username (互動式)
groupadd 建立群組 groupadd groupnamegroupadd -g 1000 groupname
groupdel 刪除群組 groupdel groupname
su 切換用戶 su - usernamesu - (切換到 root)、su -c "command" user
sudo 以其他用戶權限執行命令 sudo commandsudo -i (切換到 root)、sudo -u user commandsudo !! (重新以 sudo 執行上一個命令)
whoami 顯示當前用戶 whoamiwhoami -a (顯示所有資訊)
id 顯示用戶/群組 ID idid usernamegroups username
chmod 修改檔案權限 chmod 755 filechmod +x filechmod -R 755 dirchmod u+x,g-w,o=r file
chown 修改檔案擁有者 chown user filechown user:group filechown -R user:group dirchown :group file
chgrp 修改檔案群組 chgrp group filechgrp -R group dir
umask 顯示/設定預設權限 umaskumask 022umask 077
useradd 建立用戶 (RHEL) useradd -m -s /bin/bash useruseradd -r -s /sbin/nologin user (系統用戶)

11. 系統服務 (Systemd & Services)

指令 說明 常用用法
systemctl 管理 systemd 服務 systemctl start nginxsystemctl stop nginxsystemctl restart nginxsystemctl enable nginxsystemctl status nginxsystemctl list-units --type=servicesystemctl daemon-reload
journalctl 查看 systemd 日誌 journalctl -u nginxjournalctl -fjournalctl --no-pagerjournalctl -b (本次開機日誌)
service 舊版服務管理 service nginx startservice nginx status
crontab 設定排程工作 crontab -ecrontab -lcrontab -rcrontab file
at 一次性排程工作 echo "command" | at 10:00atqatrm jobid
shutdown 關機 shutdown -h nowshutdown -r +5shutdown -c (取消)
reboot 重新啟動 rebootreboot -p (關機)
halt 停止系統 halthalt -p (關機)
poweroff 關閉電源 poweroffpoweroff -h now
init 設定 runlevel init 0 (關機)、init 3 (多用戶)、init 5 (圖形界面)、init 6 (重啟)
cal 顯示日曆 calcal 2024cal 6 2024
timedatectl 時間設定 timedatectltimedatectl list-timezonestimedatectl set-timezone Asia/Taipei
hwclock 硬體時鐘 hwclock --showhwclock --systohc (系統時鐘 → 硬體)

12. 文件壓縮與打包進階

指令 說明 常用用法
tar 打包與壓縮 tar -czf file.tar.gz dirtar -xzf file.tar.gztar -cjf file.tar.bz2 dirtar -xvf file.tar.gz -C /pathtar --exclude="*.git" -czf file.tar.gz dir
gzip Gzip 壓縮 gzip filegzip -d file.gzgzip -c file > file.gzgzip -k file (保留原檔)
gunzip 解壓 Gzip gunzip file.gzgunzip -c file.gz > file
bzip2 Bzip2 壓縮 bzip2 filebzip2 -d file.bz2bzip2 -k file
zip Zip 壓縮 zip -r file.zip dirzip -e file.zip file (加密)、zip -j file.zip file1 file2 (去除路徑)
unzip 解壓 Zip unzip file.zipunzip -l file.zipunzip -t file.zip (檢驗)
xz XZ 壓縮 xz filexz -d file.xzxz -k filexz -9 file (最高壓縮率)
zcat 查看 Gzip 檔案 zcat file.gzzcat file.gz | grep pattern
bzcat 查看 Bzip2 檔案 bzcat file.bz2
xzcat 查看 XZ 檔案 xzcat file.xz

13. 其他實用指令 (Utilities)

指令 說明 常用用法
date 日期時間 datedate +%Y-%m-%ddate -d "2 days ago"date +%s (Unix timestamp)
cal 顯示日曆 calcal 2024cal 6 2024
bc 命令列計算器 echo "5+3" | bcbc -l (浮點數)、echo "scale=2; 10/3" | bc
jq JSON 處理 cat data.json | jqjq '.key' data.jsonjq -r '.key' data.jsonjq '.items[] | .name'
xxd 十六進位查看器 xxd filexxd -r -p hex.txt > filexxd -l 100 file (僅前 100 位元組)
base64 Base64 編碼/解碼 echo "hello" | base64echo "aGVsbG8=" | base64 -d
md5sum MD5 校驗和 md5sum filemd5sum -c checksum.md5
sha256sum SHA256 校驗和 sha256sum filesha256sum -c checksum.txt
diff 比較檔案差異 diff a bdiff -u a bdiff -r dir1 dir2diff -q a b (僅顯示差異)
wc 字詞計數 wc -l filewc -w filewc -c filewc -l /path/*
seq 產生數列 seq 1 10seq 0 2 10seq -w 1 5 (補零)
yes 重複輸出字串 yes | rm -i fileyes "text" | head -n 5
env 顯示/設定環境變數 envenv | grep PATHenv VAR=value command
printenv 顯示環境變數 printenv PATHprintenv | sort
export 匯出環境變數 export VAR=valueexport -p (列出)、export PATH=$PATH:/new/bin
alias 設定別名 alias ll='ls -la'alias (列出)、unalias ll (移除)
type 顯示指令類型 type lstype -a pythontype cd
which 查找指令位置 which lswhich -a python
whereis 查找指令/源碼/手冊 whereis pythonwhereis -b python
man 查看手冊頁 man lsman -k keywordman 2 open (查看 section 2)
info 查看 info 文檔 info bashinfo --subnodes 'bash'
help 內建指令說明 help cdhelp echohelp -d (列表)
history 歷史指令 historyhistory -c (清空)、history | grep ssh!42 (執行第 42 條)
!! 重複執行上一個指令 sudo !!!! | grepcd !:1 (上一個指令的第一個參數)
echo 輸出文字 echo "hello"echo -e "\n" (解譯脫逸字元)、echo $VARecho {a,b,c} (生成序列)
printf 格式化輸出 printf "Hello %s\n" worldprintf "%05d\n" 42
cat 顯示/串接檔案 cat filecat -n filecat a b > ccat < ( HEREDOC)
head 顯示開頭 head -n 5head -c 100 (前 100 位元組)、head -f file (持續追蹤)
tail 顯示結尾 tail -n 5tail -f file (持續追蹤)、tail -n +10 file (從第 10 行開始)
touch 建立/更新時間戳 touch filetouch -t 202401011200 filetouch -r ref target
stat 顯示檔案詳細資訊 stat filestat -c "%n %s bytes" file
rename 批量重命名 rename 's/old/new/' filesrename 'y/a-z/A-Z/' *
file 檢查文件類型 file script.shfile --mime-type ffile -i f
dd 低階拷貝工具 dd if=/dev/sda of=backup.imgdd if=/dev/zero of=file bs=1M count=100dd if=file of=/dev/null
tee 同時輸出到螢幕和檔案 command | tee output.txttee -a file (追加)、tee file1 file2
fold 折行文字 fold -w 80 filefold -s file (以空格折行)
yes 重複輸出 yes "text" | head -n 100yes | command
watch 定期執行命令 watch -n 1 'df -h'watch -n 5 'ps aux | head'
screen 終端多重視窗 screen -S sessionscreen -r sessionscreen -ls
tmux 終端多重視窗 (現代版) tmux new -s sessiontmux a -t sessiontmux lstmux kill-session -t session
crontab 排程工作 crontab -ecrontab -lcrontab -r
rsync 同步文件 rsync -av src/ dest/rsync -av --delete src/ dest/rsync -avz --progress
locate 快速搜尋檔案 locate filelocate -i PATTERNupdatedb (更新資料庫)
🎯 學習技巧: 背記不是目的,理解語義與參數才是。建議每天練習 5~10 個指令,熟悉它們的組合用法。使用 mantldr 查詢速查即可。

快速上手:常用指令速查

# 文件操作
ls -la              # 列出所有文件 (含隱藏)
touch file          # 建立空檔
cp -r src/ dest/    # 遞迴複製
rm -rf file         # 強制刪除 (危險!)

# 進程管理
ps aux | grep nginx # 查找進程
kill PID            # 終止進程
kill -9 PID         # 強制終止
top                 # 動態監視
killall nginx       # 依名稱殺進程

# 磁碟與系統
df -h               # 磁碟空間
du -sh *            # 目錄大小
free -h             # 記憶體使用
uname -a            # 系統資訊
lscpu               # CPU 資訊

# 網路
ip addr             # 網路介面
ping google.com     # 測試連通
ss -tlnp            # 監聽埠
curl -O url         # 下載檔案
wget url            # 下載 (可恢復)

# 包管理
apt update          # 更新索引 (Ubuntu)
apt install pkg     # 安裝套件
yum install pkg     # 安裝套件 (CentOS)
pip install pkg     # Python 套件
npm install pkg     # Node.js 套件
💡 Tip: 在終端機中按 TAB 可以自動補完檔案名與指令,按 / 翻找歷史指令。使用 Ctrl+R 可以反向搜尋歷史命令。

總結

Linux 命令列是經驗豐富工程師的利器。掌握基礎指令(lscdgrepfindpskilltar)後,就能用管道組合出強大的工作流程:

ps aux | grep nginx | awk '{print $2}' | xargs kill -9
🚀 記住: 命令列的威力在於「組合」 — 單個指令可能簡單,但透過管道 (|) 將它們串起來,就能完成復雜的任務。建議從 tldr 開始學習,然後逐漸掌握 man 頁的細節。