萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux ls 指令完整用法大全:從入門到進階 11 種常見參數詳解

ls 是 Linux 系統中使用頻率最高的指令之一,幾乎是打開終端機後的第一個動作。雖然每天都在用,但許多實用參數卻常被忽略。本文整理 11 種常見用法,並搭配實際輸出範例,助您掌握檔案列表的各種檢視技巧。

1. 基本列出檔案(無參數)

# ls
0001.pcap  Desktop  Downloads  index.html  install.log.syslog  Pictures  Templates
anaconda-ks.cfg  Documents  fbcmd_update.php  install.log  Music  Public  Videos

僅顯示檔名,無法得知類型、大小、權限等細節。

2. 詳細清單 -l(長格式)

# ls -l
total 176
-rw-r--r--. 1 root root   683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root  1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Desktop
...(其餘省略)

顯示權限、連結數、擁有者、大小、修改時間、檔名。注意:是小寫 L 而非數字 1。

3. 顯示隱藏檔 -a

# ls -a
.  ..  .bashrc  .cache  .config  .dbus  .gnome2  .kde  .local  .mozilla  ...

包含以 . 開頭的隱藏檔與目錄(. 為當前目錄,.. 為上層目錄)。

4. 人類可讀大小 -lh

# ls -lh
total 176K
-rw-r--r--. 1 root root 683  Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1.6K Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Desktop
...(大小以 K、M、G 單位顯示)

5. 目錄尾端加斜線 -F

# ls -F
0001.pcap  Desktop/  Downloads/  index.html  install.log.syslog  Pictures/  Templates/
anaconda-ks.cfg  Documents/  fbcmd_update.php  install.log  Music/  Public/  Videos/

目錄以 / 結尾,執行檔以 * 結尾,連結以 @ 結尾,一眼辨識類型。

6. 反向排序 -r

# ls -r
Videos  Public  Music  install.log  fbcmd_update.php  Documents  anaconda-ks.cfg
Templates  Pictures  install.log.syslog  index.html  Downloads  Desktop  0001.pcap

7. 遞迴列出子目錄 -R

# ls -R
./httpd:
total 132
-rw-r--r-- 1 root root 0 Aug 19 03:14 access_log
...
./lighttpd:
...
./nginx:
...

適合查看整棵目錄樹,輸出較長建議搭配 less 瀏覽。

8. 依修改時間新舊排序 -ltr

# ls -ltr
...(舊檔在上,新檔在下,方便找最新異動檔案)

9. 依檔案大小排序 -lS

# ls -lS
...(大檔在前,小檔在後)

10. 顯示 inode 號 -i

# ls -i
20112 0001.pcap  23610 Documents  23793 index.html  23611 Music  23597 Templates
23564 anaconda-ks.cfg  23595 Downloads  22 install.log  23612 Pictures  23613 Videos
...(第一欄為 inode 號,硬連結檔案會共用同一 inode)

11. 查看版本 --version

# ls --version
ls (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later

常用組合技速查表

參數組合用途
ls -lh詳細資訊 + 易讀大小
ls -lha含隱藏檔的詳細易讀清單
ls -lhtr依時間新舊、易讀大小、詳細資訊
ls -lSr依大小由小到大(反向)

熟練運用 ls 參數,能大幅提升終端機下的檔案管理效率。建議將常用組合設定為 alias(如 alias ll='ls -lh')寫入 ~/.bashrc,一鍵呼叫更便利。

copyright © 萬盛學電腦網 all rights reserved