第168集:文件操作
教学目标
- 掌握Shell脚本中文件的基本操作方法
- 学习文件的创建、读取、写入和修改
- 理解文件权限的管理和修改
- 掌握文件和目录的浏览与查询
- 学习文件的复制、移动和删除
- 能够在脚本中灵活处理各种文件操作
主要知识点
- 文件的基本操作
- 文件权限管理
- 文件内容操作
- 文件和目录的浏览
- 文件的复制、移动和删除
- 文件属性的查看和修改
- 文件查找和搜索
- 文件压缩和解压缩
实用案例分析
案例1:文件的基本操作
目标:学习在Shell脚本中进行文件的基本操作。
操作步骤:
- 创建文件基本操作演示脚本
# 创建脚本文件
touch file-basics.sh
# 编辑脚本文件
vim file-basics.sh
# 添加以下内容
#!/bin/bash
# 演示文件基本操作
# 1. 创建文件
echo "=== Creating files ==="
# 创建空文件
touch empty.txt
echo "Created empty.txt"
# 使用echo创建文件
echo "Hello, World!" > hello.txt
echo "Created hello.txt with content"
# 使用cat创建文件
cat > cat-file.txt << EOF
This is a file created with cat.
It has multiple lines.
EOF
echo "Created cat-file.txt with multiple lines"
# 2. 查看文件内容
echo "\n=== Viewing file content ==="
echo "Content of hello.txt:"
cat hello.txt
echo "\nContent of cat-file.txt:"
cat cat-file.txt
# 使用head查看文件头部
echo "\nFirst 2 lines of cat-file.txt:"
head -2 cat-file.txt
# 使用tail查看文件尾部
echo "\nLast 1 line of cat-file.txt:"
tail -1 cat-file.txt
# 3. 修改文件内容
echo "\n=== Modifying file content ==="
# 追加内容
echo "Appended line" >> hello.txt
echo "Appended content to hello.txt"
echo "Updated content:"
cat hello.txt
# 使用sed修改内容
sed -i 's/World/Linux/' hello.txt
echo "Modified 'World' to 'Linux' in hello.txt"
echo "Updated content:"
cat hello.txt
# 4. 查看文件属性
echo "\n=== Viewing file attributes ==="
ls -la *.txt
# 查看文件大小
echo "\nFile sizes:"
du -h *.txt
# 查看文件修改时间
echo "\nFile modification times:"
stat -c "%y %n" *.txt- 运行脚本并查看结果
# 设置执行权限
chmod +x file-basics.sh
# 运行脚本
./file-basics.sh案例2:文件权限管理
目标:学习在Shell脚本中管理文件权限。
操作步骤:
- 创建文件权限管理演示脚本
# 创建脚本文件
touch file-permissions.sh
# 编辑脚本文件
vim file-permissions.sh
# 添加以下内容
#!/bin/bash
# 演示文件权限管理
# 创建测试文件
touch test-file.txt
echo "Created test-file.txt"
# 1. 查看文件权限
echo "=== Viewing file permissions ==="
ls -la test-file.txt
# 2. 修改文件权限(使用数字表示)
echo "\n=== Modifying file permissions with numeric notation ==="
# 设置权限为 rw-r--r--
chmod 644 test-file.txt
echo "After chmod 644:"
ls -la test-file.txt
# 设置权限为 rwxr-xr-x
chmod 755 test-file.txt
echo "After chmod 755:"
ls -la test-file.txt
# 设置权限为 rw-------
chmod 600 test-file.txt
echo "After chmod 600:"
ls -la test-file.txt
# 3. 修改文件权限(使用符号表示)
echo "\n=== Modifying file permissions with symbolic notation ==="
# 给所有用户添加执行权限
chmod +x test-file.txt
echo "After chmod +x:"
ls -la test-file.txt
# 移除其他用户的写入权限
chmod o-w test-file.txt
echo "After chmod o-w:"
ls -la test-file.txt
# 设置用户的权限为读写执行
chmod u+rwx test-file.txt
echo "After chmod u+rwx:"
ls -la test-file.txt
# 4. 修改文件所有者和组
echo "\n=== Modifying file owner and group ==="
# 注意:需要root权限才能修改所有者
# 这里仅演示命令,实际执行可能需要sudo
echo "Current owner and group:"
ls -la test-file.txt
# 演示修改组(如果有权限)
# chgrp users test-file.txt
# echo "After chgrp users:"
# ls -la test-file.txt
# 5. 权限测试
echo "\n=== Testing file permissions ==="
# 测试文件是否可读
if [ -r test-file.txt ]; then
echo "test-file.txt is readable"
else
echo "test-file.txt is not readable"
fi
# 测试文件是否可写
if [ -w test-file.txt ]; then
echo "test-file.txt is writable"
else
echo "test-file.txt is not writable"
fi
# 测试文件是否可执行
if [ -x test-file.txt ]; then
echo "test-file.txt is executable"
else
echo "test-file.txt is not executable"
fi- 运行脚本并查看结果
# 设置执行权限
chmod +x file-permissions.sh
# 运行脚本
./file-permissions.sh案例3:文件内容操作
目标:学习在Shell脚本中操作文件内容。
操作步骤:
- 创建文件内容操作演示脚本
# 创建脚本文件
touch file-content.sh
# 编辑脚本文件
vim file-content.sh
# 添加以下内容
#!/bin/bash
# 演示文件内容操作
# 创建测试文件
echo "Line 1: Hello"
echo "Line 2: World"
echo "Line 3: Linux"
echo "Line 4: Shell"
echo "Line 5: Script" > content.txt
echo "Created content.txt"
# 1. 读取文件内容
echo "=== Reading file content ==="
echo "Using cat:"
cat content.txt
# 使用while循环读取
echo "\nUsing while loop:"
i=1
while read line; do
echo "Line $i: $line"
i=$((i + 1))
done < content.txt
# 2. 过滤文件内容
echo "\n=== Filtering file content ==="
# 使用grep过滤
echo "Lines containing 'Line':"
grep "Line" content.txt
# 使用sed过滤和替换
echo "\nReplacing 'Line' with 'Row':"
sed 's/Line/Row/' content.txt
# 使用awk处理
echo "\nUsing awk to print specific columns:"
awk '{print $1, $3}' content.txt
# 3. 排序文件内容
echo "\n=== Sorting file content ==="
# 创建需要排序的文件
echo "banana"
echo "apple"
echo "cherry"
echo "date" > sort-test.txt
echo "Created sort-test.txt"
echo "Original content:"
cat sort-test.txt
echo "\nSorted content:"
sort sort-test.txt
# 4. 去重文件内容
echo "\n=== Removing duplicates ==="
# 创建包含重复内容的文件
echo "apple"
echo "banana"
echo "apple"
echo "cherry"
echo "banana" > duplicate-test.txt
echo "Created duplicate-test.txt"
echo "Original content:"
cat duplicate-test.txt
echo "\nAfter deduplication:"
sort -u duplicate-test.txt
# 5. 统计文件内容
echo "\n=== Counting file content ==="
echo "Line count:"
wcl -l content.txt
echo "Word count:"
wcl -w content.txt
echo "Character count:"
wcl -c content.txt- 运行脚本并查看结果
# 设置执行权限
chmod +x file-content.sh
# 运行脚本
./file-content.sh案例4:文件和目录的浏览
目标:学习在Shell脚本中浏览文件和目录。
操作步骤:
- 创建文件和目录浏览演示脚本
# 创建脚本文件
touch file-browse.sh
# 编辑脚本文件
vim file-browse.sh
# 添加以下内容
#!/bin/bash
# 演示文件和目录的浏览
# 创建测试目录结构
mkdir -p test-dir/subdir1 test-dir/subdir2
touch test-dir/file1.txt test-dir/file2.txt test-dir/subdir1/file3.txt
echo "Created test directory structure"
# 1. 列出目录内容
echo "=== Listing directory contents ==="
echo "Current directory:"
ls -la
echo "\nTest directory:"
ls -la test-dir/
# 递归列出目录内容
echo "\nRecursive listing of test directory:"
ls -laR test-dir/
# 2. 查看当前目录
echo "\n=== Current directory ==="
echo "PWD: $PWD"
echo "Using pwd: $(pwd)"
# 3. 切换目录
echo "\n=== Changing directory ==="
# 注意:在脚本中切换目录只影响脚本执行环境,不影响外部shell
cd test-dir
echo "After cd test-dir: $(pwd)"
cd ..
echo "After cd ..: $(pwd)"
# 4. 显示目录树(使用find命令模拟)
echo "\n=== Directory tree ==="
find test-dir -type f | sort
# 5. 查看文件系统使用情况
echo "\n=== File system usage ==="
df -h
# 查看目录使用情况
echo "\nDirectory usage:"
du -h --max-depth=2 test-dir/
# 6. 查找文件
echo "\n=== Finding files ==="
# 查找特定文件
echo "Finding txt files in test directory:"
find test-dir -name "*.txt"
# 查找空文件
echo "\nFinding empty files:"
find test-dir -empty
# 查找最近修改的文件
echo "\nFinding recently modified files:"
find test-dir -type f -mtime -1- 运行脚本并查看结果
# 设置执行权限
chmod +x file-browse.sh
# 运行脚本
./file-browse.sh案例5:文件的复制、移动和删除
目标:学习在Shell脚本中复制、移动和删除文件。
操作步骤:
- 创建文件复制、移动和删除演示脚本
# 创建脚本文件
touch file-copy-move-delete.sh
# 编辑脚本文件
vim file-copy-move-delete.sh
# 添加以下内容
#!/bin/bash
# 演示文件的复制、移动和删除
# 创建测试文件和目录
mkdir -p source-dir target-dir
touch source-dir/file1.txt source-dir/file2.txt
echo "Hello" > source-dir/file1.txt
echo "World" > source-dir/file2.txt
echo "Created test files and directories"
# 1. 复制文件
echo "=== Copying files ==="
echo "Before copy:"
ls -la source-dir/ target-dir/
# 复制单个文件
cp source-dir/file1.txt target-dir/
echo "\nAfter copying file1.txt:"
ls -la source-dir/ target-dir/
# 复制多个文件
cp source-dir/*.txt target-dir/
echo "\nAfter copying all txt files:"
ls -la source-dir/ target-dir/
# 复制目录(递归)
cp -r source-dir target-dir/
echo "\nAfter copying source-dir to target-dir:"
ls -la target-dir/
# 2. 移动文件
echo "\n=== Moving files ==="
# 创建测试文件
mkdir -p move-test
touch move-test/file1.txt move-test/file2.txt
echo "Created move-test directory and files"
echo "Before move:"
ls -la move-test/
# 移动文件
mv move-test/file1.txt move-test/renamed-file.txt
echo "\nAfter renaming file1.txt:"
ls -la move-test/
# 移动文件到其他目录
mv move-test/renamed-file.txt target-dir/
echo "\nAfter moving renamed-file.txt to target-dir:"
ls -la move-test/ target-dir/
# 3. 删除文件
echo "\n=== Deleting files ==="
# 创建测试文件
mkdir -p delete-test
touch delete-test/file1.txt delete-test/file2.txt delete-test/file3.txt
echo "Created delete-test directory and files"
echo "Before deletion:"
ls -la delete-test/
# 删除单个文件
rm delete-test/file1.txt
echo "\nAfter deleting file1.txt:"
ls -la delete-test/
# 删除多个文件
rm delete-test/file2.txt delete-test/file3.txt
echo "\nAfter deleting all files:"
ls -la delete-test/
# 删除目录(空目录)
rmdir delete-test/
echo "\nAfter deleting delete-test directory:"
ls -la | grep delete-test
# 删除非空目录
rm -rf target-dir/
echo "\nAfter deleting target-dir (recursive):"
ls -la | grep target-dir
# 4. 安全删除(使用-i选项)
echo "\n=== Safe deletion ==="
touch safe-delete-test.txt
echo "Created safe-delete-test.txt"
# 注意:在脚本中使用rm -i会导致脚本等待用户输入
# 这里仅演示命令,实际使用时需要谨慎
echo "To safely delete, use: rm -i safe-delete-test.txt"
# 清理测试文件
rm safe-delete-test.txt
source-dir/- 运行脚本并查看结果
# 设置执行权限
chmod +x file-copy-move-delete.sh
# 运行脚本
./file-copy-move-delete.sh案例6:文件属性的查看和修改
目标:学习在Shell脚本中查看和修改文件属性。
操作步骤:
- 创建文件属性操作演示脚本
# 创建脚本文件
touch file-attributes.sh
# 编辑脚本文件
vim file-attributes.sh
# 添加以下内容
#!/bin/bash
# 演示文件属性的查看和修改
# 创建测试文件
touch attr-test.txt
echo "Created attr-test.txt"
# 1. 查看文件属性
echo "=== Viewing file attributes ==="
# 使用ls查看
echo "Using ls -la:"
ls -la attr-test.txt
# 使用stat查看详细属性
echo "\nUsing stat:"
stat attr-test.txt
# 使用file查看文件类型
echo "\nUsing file:"
file attr-test.txt
# 2. 修改文件时间戳
echo "\n=== Modifying file timestamps ==="
# 查看当前时间戳
echo "Current timestamps:"
stat -c "Access: %x\nModify: %y\nChange: %z" attr-test.txt
# 使用touch修改访问和修改时间
touch attr-test.txt
echo "\nAfter touch (update timestamps):"
stat -c "Access: %x\nModify: %y\nChange: %z" attr-test.txt
# 使用touch设置特定时间
touch -t 202301011200.00 attr-test.txt
echo "\nAfter touch -t (set specific time):"
stat -c "Access: %x\nModify: %y\nChange: %z" attr-test.txt
# 3. 查看和修改文件所有权
echo "\n=== Viewing and modifying file ownership ==="
# 查看当前所有权
echo "Current ownership:"
ls -la attr-test.txt
# 注意:修改所有权需要root权限
# 这里仅演示命令,实际执行可能需要sudo
echo "To change owner, use: chown username attr-test.txt"
echo "To change group, use: chgrp groupname attr-test.txt"
# 4. 查看文件的inode信息
echo "\n=== Viewing inode information ==="
echo "Inode number:"
ls -i attr-test.txt
# 查看文件系统的inode信息
echo "\nFilesystem inode information:"
df -i .
# 5. 查找硬链接和软链接
echo "\n=== Working with links ==="
# 创建硬链接
ln attr-test.txt hard-link.txt
echo "Created hard link: hard-link.txt"
# 创建软链接
ln -s attr-test.txt soft-link.txt
echo "Created soft link: soft-link.txt"
# 查看链接
echo "\nLinks:"
ls -la attr-test.txt hard-link.txt soft-link.txt
# 查看inode号(硬链接共享inode)
echo "\nInode numbers:"
ls -i attr-test.txt hard-link.txt soft-link.txt
# 测试链接
echo "Testing links..."
echo "Hello from original" > attr-test.txt
echo "Content of original:"
cat attr-test.txt
echo "Content of hard link:"
cat hard-link.txt
echo "Content of soft link:"
cat soft-link.txt
# 清理测试文件
rm attr-test.txt hard-link.txt soft-link.txt- 运行脚本并查看结果
# 设置执行权限
chmod +x file-attributes.sh
# 运行脚本
./file-attributes.sh案例7:文件查找和搜索
目标:学习在Shell脚本中查找和搜索文件。
操作步骤:
- 创建文件查找和搜索演示脚本
# 创建脚本文件
touch file-find.sh
# 编辑脚本文件
vim file-find.sh
# 添加以下内容
#!/bin/bash
# 演示文件查找和搜索
# 创建测试目录结构
mkdir -p find-test/{dir1,dir2,dir3}
touch find-test/file1.txt find-test/file2.sh find-test/dir1/file3.txt find-test/dir2/file4.sh find-test/dir3/file5.txt
echo "Created find-test directory structure"
# 1. 使用find命令查找文件
echo "=== Using find command ==="
# 查找所有文件
echo "All files in find-test:"
find find-test -type f
# 查找特定类型的文件
echo "\nAll shell scripts:"
find find-test -name "*.sh"
# 查找特定大小的文件
echo "\nFiles larger than 0 bytes:"
find find-test -type f -size +0c
# 查找特定时间修改的文件
echo "\nFiles modified in the last 7 days:"
find find-test -type f -mtime -7
# 2. 使用locate命令查找文件
echo "\n=== Using locate command ==="
# 注意:locate使用数据库,可能需要更新
echo "To update locate database, use: sudo updatedb"
echo "To find files, use: locate filename"
# 3. 使用grep在文件中搜索内容
echo "\n=== Using grep to search content ==="
# 在文件中添加内容
echo "Hello World"
echo "Linux Shell"
echo "File Search" > find-test/file1.txt
# 搜索内容
echo "Searching for 'World' in find-test:"
grep -r "World" find-test/
# 搜索包含特定模式的内容
echo "\nSearching for lines starting with 'File':"
grep -r "^File" find-test/
# 4. 结合find和grep进行复杂搜索
echo "\n=== Combining find and grep ==="
echo "Files containing 'Linux':"
find find-test -type f -exec grep -l "Linux" {} \;
# 5. 使用xargs优化搜索
echo "\n=== Using xargs for optimized search ==="
echo "Files containing 'Shell':"
find find-test -type f | xargs grep -l "Shell"
# 清理测试文件
rm -rf find-test/- 运行脚本并查看结果
# 设置执行权限
chmod +x file-find.sh
# 运行脚本
./file-find.sh案例8:文件压缩和解压缩
目标:学习在Shell脚本中压缩和解压缩文件。
操作步骤:
- 创建文件压缩和解压缩演示脚本
# 创建脚本文件
touch file-compress.sh
# 编辑脚本文件
vim file-compress.sh
# 添加以下内容
#!/bin/bash
# 演示文件压缩和解压缩
# 创建测试文件
mkdir -p compress-test
touch compress-test/file1.txt compress-test/file2.txt compress-test/file3.txt
echo "Hello" > compress-test/file1.txt
echo "World" > compress-test/file2.txt
echo "Linux" > compress-test/file3.txt
echo "Created compress-test directory and files"
# 1. 使用gzip压缩
echo "=== Using gzip ==="
# 压缩单个文件
gzip compress-test/file1.txt
echo "Compressed file1.txt with gzip"
# 查看压缩文件
ls -la compress-test/
# 解压缩
gunzip compress-test/file1.txt.gz
echo "\nDecompressed file1.txt.gz"
ls -la compress-test/
# 2. 使用zip压缩
echo "\n=== Using zip ==="
# 压缩多个文件
zip compress-test.zip compress-test/*
echo "Compressed compress-test directory with zip"
# 查看压缩文件
ls -la compress-test.zip
# 解压缩
unzip compress-test.zip -d zip-extract/
echo "\nDecompressed compress-test.zip to zip-extract/"
ls -la zip-extract/
# 3. 使用tar压缩
echo "\n=== Using tar ==="
# 创建tar归档
tar -cvf compress-test.tar compress-test/
echo "Created tar archive: compress-test.tar"
# 查看tar归档内容
tar -tvf compress-test.tar
# 解压缩tar归档
tar -xvf compress-test.tar -C tar-extract/
echo "\nDecompressed compress-test.tar to tar-extract/"
ls -la tar-extract/
# 4. 使用tar with gzip
echo "\n=== Using tar with gzip ==="
# 创建压缩归档
tar -czvf compress-test.tar.gz compress-test/
echo "Created compressed tar archive: compress-test.tar.gz"
# 查看压缩归档内容
tar -tzvf compress-test.tar.gz
# 解压缩
tar -xzvf compress-test.tar.gz -C targz-extract/
echo "\nDecompressed compress-test.tar.gz to targz-extract/"
ls -la targz-extract/
# 5. 压缩级别
echo "\n=== Compression levels ==="
# 使用不同压缩级别
for level in 1 5 9; do
echo "Compressing with level $level..."
gzip -$level -c compress-test/file2.txt > compress-test/file2-level$level.gz
echo "Level $level: $(ls -la compress-test/file2-level$level.gz | awk '{print $5}') bytes"
done
# 清理测试文件
rm -rf compress-test/ compress-test.zip compress-test.tar compress-test.tar.gz zip-extract/ tar-extract/ targz-extract/- 运行脚本并查看结果
# 设置执行权限
chmod +x file-compress.sh
# 运行脚本
./file-compress.sh课后练习
基础练习
- 创建一个脚本,统计指定目录下的文件数量和类型
- 编写一个脚本,备份指定目录到压缩文件
- 设计一个脚本,查找并删除指定目录下的空文件
进阶练习
- 创建一个脚本,监控指定文件的变化并记录日志
- 编写一个脚本,批量重命名指定目录下的文件
- 设计一个脚本,分析日志文件并提取关键信息
挑战练习
- 编写一个脚本,实现文件的增量备份
- 创建一个脚本,搜索并替换多个文件中的特定内容
- 设计一个脚本,管理用户的配置文件(备份、恢复、比较)
总结
本集详细介绍了Linux Shell脚本中的文件操作,包括文件的基本操作、权限管理、内容操作、浏览与查询、复制移动删除、属性修改、查找搜索以及压缩解压缩等内容。通过学习这些知识,读者可以在Shell脚本中灵活处理各种文件操作,实现文件的自动化管理。
文件操作是Shell脚本编程中的重要组成部分,它允许脚本与文件系统交互,实现文件的创建、修改、删除、备份等各种操作。掌握文件操作技巧是编写实用Shell脚本的基础。
通过本集的学习,读者应该能够理解和使用基本的文件操作命令,掌握文件权限的管理方法,理解文件内容的处理技巧,掌握文件和目录的浏览方法,以及学习文件的压缩和解压缩操作。这些知识将为后续学习错误处理和脚本调试打下基础。