Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

ls 指令參數完全解析:從基礎列表到遞歸排序實戰

編輯:Linux 教學

ls 是 Linux 使用頻率最高的指令,參數豐富卻常被忽略。本文系統整理核心參數、組合技巧與現代替代工具,助你精準掌控目錄列表輸出。

核心參數速查表

參數長參數功能實戰範例
-a--all顯示隱藏檔 (以 . 開頭)ls -a
-A--almost-all顯示隱藏檔但排除 . 與 ..ls -A
-l--long長格式 (權限、擁有者、大小、時間)ls -l
-h--human-readable大小人類可讀 (K/M/G)ls -lh
-F--classify檔案類型標記 (/=目錄 *=可執行 @=連結)ls -F
-r--reverse反向排序ls -lr
-R--recursive遞歸列出子目錄ls -R
-S--sort=size依大小排序 (大→小)ls -lS
-t--sort=time依修改時間排序 (新→舊)ls -lt
-X--sort=extension依副檔名排序ls -lX
-1--format=single-column單欄輸出 (腳本處理友善)ls -1
-i--inode顯示 inode 號ls -li
--color=auto彩色輸出 (預設開啟)ls --color=never 關閉

黃金組合拳

ls -lhF        # 人類可讀大小 + 類型標記 (日常最常用)
ls -lht        # 長格式 + 人類可讀 + 時間排序 (找最新檔案)
ls -lhS        # 長格式 + 人類可讀 + 大小排序 (找大檔案)
ls -lA         # 長格式 + 含隱藏檔 (排除 . ..)
ls -lR         # 遞歸長格式 (配合 grep 找檔案)
ls -l --time-style=full-iso  # 完整 ISO 時間格式 (含秒、時區)

輸出欄位詳細解讀 (ls -l)

-rw-r--r--  1 user  group  1024  Jan 15 10:30  file.txt
│││││││   │  │    │     │          │        │
│││││││   │  │    │     │          │        └─ 檔名
│││││││   │  │    │     │          └─ 修改時間
│││││││   │  │    │     └─ 檔案大小 (位元組)
│││││││   │  │    └─ 群組名
│││││││   │  └─ 擁有者
│││││││   └─ 連結數
││││││└─ 其他人權限 (r=讀 w=寫 x=執行 -=無)
│││││└─ 群組權限
││││└─ 擁有者權限
│││└─ 檔案類型 (-=一般檔 d=目錄 l=連結 b=區塊裝置 c=字元裝置 p=管道 s=Socket)
││└─ (保留)
│└─ (保留)
└─ (保留)

現代替代工具

  • exa (Rust 編寫):exa -lh --git 內建 Git 狀態、彩色、樹狀 -T、預設人類可讀
  • lsd:類 exa,圖示豐富、Nerd Font 支援
  • tree:tree -L 2 -h 專注樹狀結構
# 安裝
# CentOS/RHEL/Fedora
dnf install exa lsd tree
# Debian/Ubuntu
apt install exa lsd tree
# Arch
pacman -S exa lsd tree

腳本處理最佳實踐

# 避免解析 ls 輸出 (檔案名含換行/空格會出錯)
# 推薦使用 find 或 glob
for f in *; do
  [ -f "$f" ] && echo "File: $f"
done

# 或 find 配合 -print0 / xargs -0
find . -maxdepth 1 -type f -print0 | xargs -0 ls -l

結語

熟練 ls -lhF、-lht、-lhS 三大組合覆蓋 90% 場景;腳本嚴禁解析 ls 輸出,改用 find 或 Shell glob;日常互動體驗升級請嘗試 exa 或 lsd。

Copyright © Windows教程網 All Rights Reserved