在Linux中,重定向是Shell中非常重要的功能,主要用于控制命令的输入输出流向。以下是Linux中常见的重定向方式及其详细说明:
>:覆盖写入文件bash
command > file.txt # 将命令的输出覆盖写入file.txt(文件原有内容会被清空)>>:追加写入文件bash
command >> file.txt # 将命令的输出追加到file.txt末尾2>:覆盖写入错误信息bash
command 2> error.log # 将命令的错误信息覆盖写入error.log2>>:追加写入错误信息bash
command 2>> error.log # 将错误信息追加到error.log&> 或 >&:同时重定向stdout和stderr(覆盖)bash
command &> output.log # 标准输出和错误一起覆盖写入output.log&>>:同时追加stdout和stderrbash
command &>> output.log # 标准输出和错误一起追加到output.logbash
command > file.txt 2>&1 # 先重定向stdout到file.txt,再将stderr合并到stdout<:从文件读取输入bash
command < input.txt # 将input.txt内容作为command的输入<<(Here Document):直接嵌入多行输入bash
command << EOF
line1
line2
EOF<<<(Here String):直接传入字符串bash
command <<< "text input" # 将字符串作为command的输入/dev/null:丢弃输出bash
command > /dev/null # 丢弃stdout
command 2> /dev/null # 丢弃stderr
command &> /dev/null # 丢弃所有输出/dev/stdin、/dev/stdout、/dev/stderr:显式指定流bash
command > /dev/stdout 2> /dev/stderrbash
command 3> file.txt # 将自定义文件描述符3重定向到file.txtbash
command > file.txt 2>&3 # 将stderr重定向到文件描述符3指向的位置bash
command 3<&- # 关闭文件描述符3的输入虽然不是严格的重定向,但管道常用于流传递:
command1 | command2 # 将command1的stdout作为command2的stdin
bash
command > output.log 2> error.logbash
command &> /dev/nulltee命令):bash
command | tee file.txt0(stdin)、1(stdout)、2(stderr)。2>&1 > file 和 > file 2>&1 效果不同。掌握这些重定向技巧可以高效管理命令的输入输出流,尤其在日志处理和自动化脚本中非常实用。