ls 是 list 的縮寫,也是 Linux 下最常用的指令之一。它用來列出當前目錄的清單,若指定其他目錄則顯示該目錄的檔案與子目錄,透過參數還能檢視檔案的詳細資訊,輸出也能彩色加亮以區分檔案類型。
用法:ls [選項] [目錄名]
功能:列出目標目錄中所有的子目錄與檔案。
-a:列出所有檔案,包含以 . 開頭的隱藏檔。
-A:列出除了 . 與 .. 以外的所有項目。
-C:多列輸出,為預設行為。
-l:以單列格式輸出,除檔名外還列出權限、擁有者、大小等詳細資訊。
-R(--recursive):同時列出所有子目錄層級。
-F:在每個項目後加上類型標記,* 代表可執行的普通檔案、/ 代表目錄、@ 代表符號連結、| 代表命令管道 FIFO、= 代表 socket;普通檔案不加標記。
-m:以逗號分隔並填滿整行。
-i:顯示 inode 編號,一個 inode 代表一個檔案。
-t:依修改時間排序。
-d(--directory):把目錄當成檔案顯示,不展開其內容。
-n:印出 UID 與 GID。
-h:以易讀單位顯示檔案大小。
(1) ls -l(等同 ll),以單行單項列出 /boot 的詳細資訊:
[root@localhost boot]# ls -l 總用量 89404 -rw-r--r--. 1 root root 123838 3月 6 2015 config-3.10.0-229.el7.x86_64 drwxr-xr-x. 2 root root 26 3月 21 02:27 grub drwxr-xr-x. 6 root root 104 3月 21 02:43 grub2 -rw-r--r--. 1 root root 43536327 3月 21 02:41 initramfs-0-rescue-35667f30fcac420f933d23d8835c4cf3.img -rw-r--r--. 1 root root 2881257 3月 6 2015 System.map-3.10.0-229.el7.x86_64 -rwxr-xr-x. 1 root root 5029136 3月 21 02:41 vmlinuz-0-rescue-35667f30fcac420f933d23d8835c4cf3
(2) ls -C(等同 ls),多列填滿輸出:
[root@localhost boot]# ls config-3.10.0-229.el7.x86_64 initrd-plymouth.img grub symvers-3.10.0-229.el7.x86_64.gz grub2 System.map-3.10.0-229.el7.x86_64
(3) ls -R 遞迴顯示當前目錄下所有檔案:
[root@localhost boot]# ls -R .: config-3.10.0-229.el7.x86_64 grub grub2 initrd-plymouth.img ... ./grub: splash.xpm.gz ./grub2: device.map fonts grub.cfg grubenv i386-pc locale themes ./grub2/fonts: unicode.pf2 ./grub2/i386-pc: acpi.mod ata.mod ext2.mod linux.mod normal.mod xfs.mod ...
(4) ls -R boot/grub2 遞迴顯示指定目錄。
(5) ls -n 印出 UID 與 GID:
[root@localhost sunjimeng]# ls -n 總用量 4588 -rw-------. 1 1000 1000 4694016 4月 14 21:54 core.3246 drwxr-xr-x. 2 0 0 4096 4月 26 03:38 empty drwxr-xr-x. 2 1000 1000 6 4月 19 03:30 桌面
(6) ls -m 以逗號分隔水平列出:
core.3246, empty, text, 公共, 模板, 視頻, 圖片, 文檔, 下載, 音樂, 桌面
(7) ls -t 依修改時間排序輸出詳細資訊,最新的檔案會排在前面。
(8) ls -ihl 同時顯示 inode(-i)與易讀大小(-h):
總用量 4.5M 2843373 -rw-------. 1 sunjimeng sunjimeng 4.5M 4月 14 21:54 core.3246 272893290 drwxr-xr-x. 2 root root 4.0K 4月 26 03:38 empty 406101499 drwxr-xr-x. 2 root root 32 4月 22 22:29 text
(9) ls -d 只顯示目錄本身,不展開內容:
drwx------. 16 sunjimeng sunjimeng 4096 4月 29 00:36 .
(10) ls -F /boot 以類型標記顯示各子項:
config-3.10.0-229.el7.x86_64 grub/ grub2/ initrd-plymouth.img vmlinuz-0-rescue-35667f30fcac420f933d23d8835c4cf3* vmlinuz-3.10.0-229.el7.x86_64*
(11) ls -a 與 ls -A 的差異:-a 會列出 . 與 ..,因此比 -A 多出兩項。
(12) ls -F /boot | grep /$ 只列出子目錄:
grub/ grub2/
(13) ls -lF /boot | grep /$ 與 ls -lF /boot | grep "^d" 結果相同,差別只在 -F 會在目錄名後加上 / 並以紅色標示。
(14) ls -l /boot | grep "^d" 與 grep "^drw" 效果一致,都是用來篩出目錄。
(15) ls | sed "s:^:`pwd`/:" 為每個項目補上絕對路徑:
/home/sunjimeng/core.3246 /home/sunjimeng/empty /home/sunjimeng/桌面
在 /etc/bashrc 中加入一行:
alias ls="ls --color"
下次啟動 bash 就會看到彩色清單,顏色含義大致為:藍色是目錄、綠色是可執行檔、紅色是壓縮檔、淺藍色是連結、灰色是其他檔案。
延伸閱讀:https://www.cnblogs.com/peida/archive/2012/10/23/2734829.html 、https://man.linuxde.net/ls