← 中文资源

简体中文版本

Bash 输入输出重定向与文件描述符

演示 stdout 覆盖与追加、stderr 丢弃、合并双流、分别重定向、here string、自定义文件描述符、tee 多目标输出等技巧。

阅读英文原文

功能说明

脚本系统演示 I/O 重定向:用 > 覆盖写日志、>> 追加;把错误丢弃到 /dev/null;用 &> 合并标准输出和标准错误;用大括号分组分别捕获两个流;用 here string 把一行文本喂给 read;用 exec 打开和关闭自定义文件描述符 3、4;用 tee 同时写入多个目标。

关键代码

  • echo "Info message" > "$logfile" 覆盖写入,>> 追加;重定向在命令执行前由 shell 完成。
  • ls /nonexistent 2>/dev/null || true 只丢弃标准错误,|| true 防止 set -e 中断脚本。
  • ls /etc /nonexistent &>"${logfile}.all" 把 stdout 与 stderr 一起写入同一文件。
  • { echo ...; echo ... >&2; } > /tmp/stdout.txt 2> /tmp/stderr.txt 用分组让两条流分别落盘,组内 >&2 显式写标准错误。
  • exec 3> /tmp/custom-fd.txt 打开描述符 3,echo "Line 1" >&3 写入,exec 3>&- 关闭;exec 4< /etc/hostname 与 read -r hostname <&4 演示读描述符。
  • echo "Broadcast" | tee /tmp/file1.txt /tmp/file2.txt /dev/null 把内容复制到多个文件并保留 stdout。

使用注意

&> 是 Bash 扩展,POSIX sh 应写成 >file 2>&1,且顺序不能颠倒。描述符 3 以上可用,但打开后必须关闭,避免影响后续命令。重定向会先截断目标文件,即使命令随后失败,原内容也可能已丢失。2>/dev/null 会掩盖真实错误,调试阶段应谨慎使用。

验证方式

执行后检查 output.log 含两行、output.log.all 同时含正常列表与错误信息、/tmp/stdout.txt 与 /tmp/stderr.txt 各自只含对应内容;First: hello, Second: world、Hostname: 以及两个广播文件内容均应符合预期。

代码示例

#!/usr/bin/env bash
set -euo pipefail

logfile="output.log"

# Basic redirection
echo "Info message" > "$logfile"
echo "More info" >> "$logfile"

# Redirect stderr to /dev/null
ls /nonexistent 2>/dev/null || true

# Redirect both stdout and stderr
ls /etc /nonexistent &>"${logfile}.all" || true

# Redirect stdout and stderr separately
{
    echo "This goes to stdout"
    echo "This goes to stderr" >&2
} > /tmp/stdout.txt 2> /tmp/stderr.txt

# Here-string
read -r first second <<< "hello world"
echo "First: $first, Second: $second"

# Custom file descriptors
exec 3> /tmp/custom-fd.txt
echo "Line 1" >&3
echo "Line 2" >&3
exec 3>&-

# Read from file using fd
exec 4< /etc/hostname
read -r hostname <&4
exec 4<&-
echo "Hostname: $hostname"

# Redirect to multiple targets
echo "Broadcast" | tee /tmp/file1.txt /tmp/file2.txt /dev/null

# Conditional redirection
debug=true
if [[ "$debug" == true ]]; then
    echo "Debug info" >&2
fi