目录
一、文件与目录管理基础
创建文件
# 创建空文件 [root@zhangsan101 ~]# touch a1.txt # 批量创建文件(使用 brace expansion 语法) [root@zhangsan101 ~]# touch m{1..5}.txt # 创建m1.txt到m5.txt # 创建可执行脚本文件 [root@zhangsan101 ~]# touch s2.sh [root@zhangsan101 ~]# chmod +x s2.sh
创建目录
# 创建单级目录 [root@zhangsan101 ~]# mkdir ff # 批量创建目录 [root@zhangsan101 ~]# mkdir t{1..3} # 创建t1、t2、t3目录 # 创建多级目录(-p选项自动创建父目录) [root@zhangsan101 ~]# mkdir -p aa/bb/cc/dd/ee
目录结构查看
# 安装tree工具(若未安装) [root@zhangsan101 ~]# yum install -y tree # 查看目录树结构 [root@zhangsan101 ~]# tree aa aa/ └── bb └── cc └── dd └── ee
二、链接文件深入理解
Linux 中有两种链接文件:软链接(符号链接)和硬链接,创建与区别如下:
创建软链接
# 对文件创建软链接 [root@zhangsan101 ~]# ln -s a1.txt a11.txt # 对目录创建软链接 [root@zhangsan101 ~]# ln -s /etc/yum a22
创建硬链接
# 只能对文件创建硬链接,不能对目录创建 [root@zhangsan101 ~]# ln m1.txt m1_link.txt
核心区别对比
特性 软链接 硬链接 inode 号 不同 相同 跨文件系统 支持 不支持 对目录支持 支持 不支持 源文件删除后 失效(断链) 仍可使用 大小 仅记录路径 与源文件相同 验证命令:
# 查看inode号 [root@zhangsan101 ~]# ls -li a1.txt a11.txt # 软链接inode不同 [root@zhangsan101 ~]# ls -li m1.txt m1_link.txt # 硬链接inode相同 # 测试源文件删除后链接状态 [root@zhangsan101 ~]# rm -f a1.txt [root@zhangsan101 ~]# cat a11.txt # 软链接提示"没有那个文件或目录"
三、文件压缩与解压缩全攻略
Linux 系统常用的压缩工具有 gzip、bzip2、xz 三种,配合 tar 命令使用:
1、压缩命令对比
# gzip压缩(tar选项-z)
[root@zhangsan101 ~]# tar -zcf etc_gzip.tar.gz /etc/
# bzip2压缩(tar选项-j)
[root@zhangsan101 ~]# tar -jcf etc_bzip2.tar.bz2 /etc/
# xz压缩(tar选项-J)
[root@zhangsan101 ~]# tar -Jcf etc_xz.tar.xz /etc/
2、解压缩命令
# 解压到当前目录
[root@zhangsan101 ~]# tar -zxf etc_gzip.tar.gz
# 解压到指定目录(-C选项)
[root@zhangsan101 ~]# tar -jxf etc_bzip2.tar.bz2 -C /tmp/
3、三种压缩方式性能对比
[root@zhangsan101 ~]# du -sh /etc/ etc_*.tar*
42M /etc/
12M etc_gzip.tar.gz # 压缩比最小,速度最快
11M etc_bzip2.tar.bz2 # 压缩比中等,速度中等
8.3M etc_xz.tar.xz # 压缩比最大,速度最慢
4、通用解压技巧
不知道压缩类型时,先用 file 命令识别,再用 tar 通用解压:
[root@zhangsan101 ~]# file unknown.tar.*
unknown.tar.xz: XZ compressed data
# 无需指定压缩类型,tar自动识别
[root@zhangsan101 ~]# tar -xf unknown.tar.xz
四、文件查找与搜索
find 命令是 Linux 中强大的文件搜索工具,常用用法:
1、按文件名查找
# 精确匹配文件名
[root@zhangsan101 ~]# find /etc -name "hosts"
# 模糊匹配(不区分大小写)
[root@zhangsan101 ~]# find /var -iname "*.log"
2、按文件属性查找
# 按拥有者查找
[root@zhangsan101 ~]# find /home -user zhangsan
# 按文件大小查找(+表示大于,-表示小于)
[root@zhangsan101 ~]# find /var/log -size +10M # 查找大于10M的文件
3、组合条件查找
# 查找7天前修改的普通文件并删除(谨慎使用!)
[root@zhangsan101 ~]# find /tmp -type f -mtime +7 -delete