通过14个示例彻底掌握 linux ls 命令的使用

Linux / UNIX 中的 ls 命令用于列出目录内容。当我们不带任何选项运行 ls 命令时,它显示当前目录下的有关文件信息,按字母顺序排列。

ls 命令语法

$ ls <options> <file | directory>

ls-command-options-linux

在本教程中,我们将通过 14 个有用的实际示例介绍 Linux 中的 ls 命令。

(1) 列出当前工作目录的内容

当我们运行不带任何选项的 ls 命令时,它将列出如下所示的文件和目录

$ ls
Desktop Documents Downloads Music myscript.sh Pictures playbook.yaml Public snap Templates Videos
$

(2) 以长列表格式列出内容

使用 ls 命令中的 -l 选项,以长列表格式列出目录内容。

long-listing-format-ls-command

如上所示,ls -l 还显示了文件和目录的权限、修改时间和大小。

(3) 列出特定目录的内容

要列出特定目录的内容,示例如下:

$ ls -l /var/log/apt/

list-contents-specific-directory

如果你只希望列出目录权限,那么使用-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

Directory-Contents-Sorted-by-Time

按修改时间倒序列出文件,使用如下命令:

$ ls -ltr

(6) 以人类可读格式列出内容

ls 命令中的 -h 选项用于以人可读格式列出文件大小 (2K、34M 或 5G)。

$ ls -lh

List-contents-in-human-readable-format

(7) 列出隐藏文件

ls 命令中的 -a 选项用于列出目录下的所有文件,包括隐藏文件。

$ ls -la /home/linuxtechi/

Hidden-List-ls-command

(8) 递归列出文件和目录

ls 命令中使用 -R 选项,可以递归列出文件和目录,示例如下

$ ls -R /etc/

List-files-directort-recursively

(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

List-files-sorted-by-size

(10) 列出文件和目录索引节点编号

To list inode numbers of file and directory using ls command then use ‘-i’ option,

使用使用 -i 选项, 可以列出文件和目录的 inode 号

$ ls -li

Listing-inodes-file-directories-ls-command

(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

Format-ls-command-output

以单列输出

$ ls -1

Listing-Output-in-Single-Column

(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

List-UID-GID-ls-command-output

(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"

Timestamp-ls-command-output

我的开源项目

酷瓜云课堂-在线教育解决方案

猜你喜欢

转载自blog.csdn.net/xiaochong0302/article/details/129118923
今日推荐