重定向 #
一、输出重定向 #
bash
#!/bin/bash
# 覆盖写入
echo "Hello" > file.txt
# 追加写入
echo "World" >> file.txt
# 重定向错误
ls /nonexistent 2> error.log
# 重定向所有输出
ls /nonexistent &> all.log
二、输入重定向 #
bash
#!/bin/bash
# 从文件读取
while read line; do
echo "$line"
done < file.txt
# Here Document
cat << EOF
多行文本
第二行
EOF
# Here String
grep "pattern" <<< "search in this string"
三、文件描述符 #
| 描述符 | 说明 |
|---|---|
| 0 | 标准输入 |
| 1 | 标准输出 |
| 2 | 标准错误 |
bash
#!/bin/bash
# 重定向到不同文件
command > stdout.log 2> stderr.log
# 合并输出
command > all.log 2>&1
# 丢弃输出
command > /dev/null 2>&1
下一步 #
你已经掌握了重定向,接下来让我们学习 管道!
最后更新:2026-03-27