Linux / UNIX 中的 ls 指令用于列出目錄内容。當我們不帶任何選項運作 ls 指令時,它顯示目前目錄下的有關檔案資訊,按字母順序排列。
ls 指令文法
$ ls <options> <file | directory>
在本教程中,我們将通過 14 個有用的實際示例介紹 Linux 中的 ls 指令。
(1) 列出目前工作目錄的内容
當我們運作不帶任何選項的 ls 指令時,它将列出如下所示的檔案和目錄
$ ls
Desktop Documents Downloads Music myscript.sh Pictures playbook.yaml Public snap Templates Videos
$
(2) 以長清單格式列出内容
使用 ls 指令中的 -l 選項,以長清單格式列出目錄内容。
如上所示,ls -l 還顯示了檔案和目錄的權限、修改時間和大小。
(3) 列出特定目錄的内容
要列出特定目錄的内容,示例如下:
$ ls -l /var/log/apt/
如果你隻希望列出目錄權限,那麼使用-ld 選,示例如下:
$ ls -ld /var/log/apt/
drwxr-xr-x 2 root root 4096 Oct 14 06:58 /var/log/apt/
$
(4) 顯示目錄内容的檔案類型 (ls -F)
To list file types with ls command then use ‘-F’ option, in the
following example, we are listing the file types from present working
directory
ls 指令使用 -F 選項,可以列出檔案類型,示例如下:
$ ls -F
Desktop/ Documents/ Downloads/ Music/ myscript.sh* Pictures/ playbook.yaml Public/ snap/ Templates/ Videos/
$
在上面的輸出中,将為各自的類型追加以下内容:
- ‘/’ – directory
- normal files – nothing
-
- – executable file
- @ – link file
(5) 按時間排序的清單内容
ls 指令中使用 -t 選項,按時間排序列出目錄内容。
$ ls -lt
按修改時間倒序列出檔案,使用如下指令:
$ ls -ltr
(6) 以人類可讀格式列出内容
ls 指令中的 -h 選項用于以人可讀格式列出檔案大小 (2K、34M 或 5G)。
$ ls -lh
(7) 列出隐藏檔案
ls 指令中的 -a 選項用于列出目錄下的所有檔案,包括隐藏檔案。
$ ls -la /home/linuxtechi/
(8) 遞歸列出檔案和目錄
ls 指令中使用 -R 選項,可以遞歸列出檔案和目錄,示例如下
$ ls -R /etc/
(9) 按大小排序列出檔案 (ls -lhs)
Use ‘-lhs’ option in ls command to list file sorted by size (human readable size like K, M & G), example is shown below:
使用 -lhs 選項按大小 (人類可讀的格式如 K, M 和 G)列出檔案,示例如下:
$ ls -lhS
(10) 列出檔案和目錄索引節點編号
To list inode numbers of file and directory using ls command then use ‘-i’ option,
使用使用 -i 選項, 可以列出檔案和目錄的 inode 号
$ ls -li
(11) 格式化 ls 指令輸出
ls 指令的輸出可以使用 --format 選項進行格式化。
基本文法:
$ ls --format=WORD
支援格式:
- across -x
- commas -m
- horizontal -x, long -l
- single-column -1
- verbose -l
- vertical -C
$ ls -m
or
$ ls --format=commas
以單列輸出
$ ls -1
(12) 列出檔案和目錄的 uid 和 gid
To list file’s and directory’s UID and GID with ls command, use ‘-n’ option, example is shown below
使用-n 選項,列出檔案和目錄的 UID 和 GID,示例如下
$ ls -n
(13) 檢視 ls 指令的預設别名
Type the alias and grep command on the terminal to display the default aliases set for ls command.
在終端上輸入 alias 和 grep 指令,将顯示 ls 指令設定的預設别名。
$ alias | grep ls
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
$
(14) 回顯中啟用時間戳
$ ls -l --time-style="+%Y-%m-%d $newline%m-%d %H:%M"
我的開源項目
- course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
- course-tencent-cloud(酷瓜雲課堂 - github倉庫)