ls 浏览目录内容
常用:-l(长列表)、-a(显示隐藏)、-h(友好大小)、-t(按时间排序)、-r(反向)
进阶:
ls -i查看硬盘唯一编号inode,唯一存在,如果相同则代表此文件为链接文件
tm@server1:~$ touch file1
tm@server1:~$ ln file1 file2 #硬链接
tm@server1:~$ ls -li
total 4
2797 drwxrwxr-x 2 tm tm 4096 Mar 17 17:33 a
2798 lrwxrwxrwx 1 tm tm 1 Mar 17 17:35 b -> a
2800 -rw-rw-r-- 2 tm tm 0 Mar 17 17:44 file1
2800 -rw-rw-r-- 2 tm tm 0 Mar 17 17:44 file2
touch创建文件ln创建硬链接ln 源文件 目标文件,目标文件只是给个名字不需要存在。原因文件名必须唯一,加上 -f 选项(ln -f a b),系统会强制先删除原有的 b,再创建新的链接。小心使用
2. ls -R 递归查看目录树
tm@server1:~$ mkdir a/b
tm@server1:~$ ls -R a
a:
b
a/b:
结合
grep可以搜索文件,虽然说find更方便
tm@server1:~$ ls -R /etc | grep ".conf"
adduser.conf
grep文本搜索
3. ls -lS 文件按照大小排序,
# 找出当前目录最大的3个文件,前4行
# -l 长列表,-S 按大小排序,-h 可读格式
tm@server1:~$ ls -lSh /etc/ | head -4
total 920K
-rw-r--r-- 1 root root 74K Jul 12 2023 mime.types
-rw-r--r-- 1 root root 22K Mar 17 15:33 ld.so.cache
-rw-r--r-- 1 root root 13K Mar 28 2021 services
# 找出当前目录最小的3个文件,前4行
# 加了 -r,从小到大
tm@server1:~$ ls -lSrh /etc/ | head -4
total 920K
-rw-r--r-- 1 root root 0 Aug 6 2025 subuid-
-rw-r--r-- 1 root root 0 Aug 6 2025 subgid-
-rw-r--r-- 1 root root 8 Aug 6 2025 timezone
head打印输出内容的前几行,|管道符,将前面的输出作为下一个的输入
4. ls -d */只列出目录,不列文件*/ 是一个通配符,匹配所有以 / 结尾的条目(即目录)-d 参数告诉 ls 不要进入目录内部,只列出目录本身
tm@server1:~$ ls -d */
a/ b/
tm@server1:~$ ls -d /home/tm/*/
/home/tm/a/ /home/tm/b/
ls -F文件类型分类-F会在条目后面加一个指示符/:目录*:可执行文件@:符号链接|:管道=:套接字
tm@server1:~$ ls -F
a/ b@ file1 file2
ls -l --time-style自定义时间格式
# 显示完整的时间(年月日时分秒)
tm@server1:~$ ls -l --time-style=long-iso
total 4
drwxrwxr-x 3 tm tm 4096 2026-03-17 17:46 a
lrwxrwxrwx 1 tm tm 1 2026-03-17 17:35 b -> a
-rw-rw-r-- 2 tm tm 0 2026-03-17 17:44 file1
-rw-rw-r-- 2 tm tm 0 2026-03-17 17:44 file2
# 或者自定义格式
tm@server1:~$ ls -l --time-style="+%Y-%m-%d %H:%M:%S"
total 4
drwxrwxr-x 3 tm tm 4096 2026-03-17 17:46:55 a
lrwxrwxrwx 1 tm tm 1 2026-03-17 17:35:01 b -> a
-rw-rw-r-- 2 tm tm 0 2026-03-17 17:44:23 file1
-rw-rw-r-- 2 tm tm 0 2026-03-17 17:44:23 file2
通配符用法
ls *.conf # 所有 .conf 文件
ls file?.txt # file1.txt, file2.txt, ...(一个字符)
ls file[0-9].txt # file0.txt, file1.txt, ... 到 file9.txt
ls file[!0-9].txt # 文件名包含 file,后面跟一个非数字字符
高手案例
找出最近修改的5个日志文件:
ls -lt /var/log/*.log | head -5
统计当前目录下普通文件的数量(不包含目录):
ls -l | grep "^-" | wc -l
wc统计
(grep "^-" 匹配以 - 开头的行,即普通文件)
3. 找到最大的3个文件并显示完整信息:
ls -lSh | grep "^-" | head -3
#grep "^-" 先过滤掉目录,只留文件,再排序取前3
以可读大小排序,但只显示前5个文件,并用反色高亮:
ls -lSh | grep "^-" | head -5 | less -R
#less -R 可以保留颜色,方便查看。less分页查看
less分页查看内容
5. 按修改时间倒序,但只显示最新的3个目录:
ls -dt */ | head -3
#-d 防止进入目录,*/ 只选目录,-t 按时间排序,head 取前3