首先,让我们理解 Linux 中的三种基本数据流:
让我们通过一个完整的例子来展示这些重定向操作符的使用:
# 1. 创建一个基本的日志系统
# 使用 > 创建初始日志文件
echo "=== 系统日志开始 ===" > system.log
# 使用 >> 追加日志条目
date >> system.log
echo "系统启动" >> system.log
# 使用 2> 记录错误
find /root -name "*.conf" 2> errors.log
# 使用 Here Document 添加多行配置
cat << EOF > config.txt
服务器名称:主服务器
IP地址:192.168.1.1
端口:8080
EOF
# 使用 Here String 进行快速搜索
grep "服务器" <<< "这是主服务器的配置"
# 使用管道组合命令
cat config.txt | grep "IP" | cut -d ":" -f 2
# 同时处理标准输出和错误
./script.sh &> full_log.txt
让我们看一个更复杂的场景,展示如何组合使用这些操作符:
#!/bin/bash
# 创建一个完整的日志处理系统
{
echo "=== 处理开始 ==="
# 使用 Here Document 处理多行输入
cat << EOF | while read line; do
echo "处理: $line"
done >> processed.log
数据1
数据2
数据3
EOF
# 同时处理标准输出和错误,并将它们分开存储
find /var/log -type f -name "*.log" \
> found_files.txt \
2> search_errors.txt
# 使用 Here String 进行数据验证
if grep -q "错误" <<< "$(cat search_errors.txt)"; then
echo "发现错误" | tee -a errors_summary.log
fi
echo "=== 处理结束 ==="
} | tee complete_log.txt
>
重定向时要小心,因为它会覆盖现有文件。如果不确定,最好使用 >>
进行追加。command > output.log 2> error.log
因篇幅问题不能全部显示,请点此查看更多更全内容