文件读写 #
一、读取文件 #
bash
#!/bin/bash
# 读取整个文件
content=$(cat file.txt)
# 逐行读取
while IFS= read -r line; do
echo "$line"
done < file.txt
# 读取到数组
mapfile -t lines < file.txt
# 读取前N行
head -n 10 file.txt
# 读取后N行
tail -n 10 file.txt
二、写入文件 #
bash
#!/bin/bash
# 覆盖写入
echo "内容" > file.txt
# 追加写入
echo "内容" >> file.txt
# 写入多行
cat > file.txt << EOF
第一行
第二行
EOF
# 使用tee
echo "内容" | tee file.txt
三、文件操作函数 #
bash
#!/bin/bash
read_file() {
local file="$1"
[[ -f "$file" ]] && cat "$file"
}
write_file() {
local file="$1"
local content="$2"
echo "$content" > "$file"
}
append_file() {
local file="$1"
local content="$2"
echo "$content" >> "$file"
}
下一步 #
你已经掌握了文件读写,接下来让我们学习 文件权限!
最后更新:2026-03-27