I/O(输入/输出)重定向是Linux/Unix系统中一个强大且基础的功能,它允许用户控制命令的输入来源和输出去向。下面我将详细介绍Linux中的I/O重定向机制。
在Linux中,每个进程默认会打开三个文件描述符: - 0:标准输入(stdin) - 1:标准输出(stdout) - 2:标准错误(stderr)
command > file
将命令的标准输出重定向到文件(覆盖原有内容)
command >> file
将命令的标准输出追加到文件末尾
command 2> file
将标准错误输出重定向到文件
command 2>> file
将标准错误输出追加到文件
command > file 2>&1
将标准输出和标准错误都重定向到同一个文件
command &> file
上述写法的简写形式(bash 4.0+)
command > stdout.txt 2> stderr.txt
将标准输出和标准错误分别重定向到不同文件
command < file
使用文件内容作为命令的标准输入
command << delimiter
...
delimiter
Here文档(here-document),将两个delimiter之间的内容作为输入
command <<< "string"
Here字符串(here-string),将字符串作为输入
command > /dev/null
丢弃标准输出
command 2> /dev/null
丢弃标准错误
command > /dev/null 2>&1
丢弃所有输出
echo "Error message" >&2
将消息输出到标准错误
command1 2>&1 | command2
将command1的标准输出和标准错误都通过管道传递给command2
command >file 2>&1
等同于:
command 1>file 2>&1
exec 3> file
创建文件描述符3并指向文件
echo "test" >&3
向文件描述符3写入内容
exec 3>&-
关闭文件描述符3
command <(subcommand)
将subcommand的输出作为文件提供给command
command >(subcommand)
将command的输出提供给subcommand作为输入
command | tee file
将输出同时显示在屏幕和写入文件
command | tee -a file
追加模式
command > file 2>&1 # 正确
command 2>&1 > file # 错误(不会达到预期效果)
script.sh > output.log 2>&1
make > build.log 2> errors.log
noisy_command > /dev/null 2>&1
cat << EOF > config.txt
server {
port = 8080
host = "localhost"
}
EOF
{ command1; command2; } > combined_output.txt
掌握I/O重定向可以极大地提高在Linux命令行环境下的工作效率,是每个Linux用户和系统管理员必备的技能。