Linux重定向操作详解
Linux 重定向详解
在Linux中,重定向是一种强大的功能,允许你控制命令的输入来源和输出去向。以下是关于Linux重定向的全面介绍:
标准输入输出流
Linux中有三种标准数据流:
- 标准输入(stdin) - 文件描述符0,通常是键盘输入
- 标准输出(stdout) - 文件描述符1,通常是终端显示
- 标准错误(stderr) - 文件描述符2,通常是错误消息输出
基本重定向操作
1. 输出重定向
-
>
将stdout重定向到文件(覆盖)ls > filelist.txt
-
>>
将stdout追加到文件echo "新内容" >> existingfile.txt
-
2>
将stderr重定向到文件command_not_found 2> error.log
-
&>
将stdout和stderr都重定向到文件some_command &> output_and_error.log
2. 输入重定向
-
<
从文件读取stdinsort < unsorted.txt
-
<<
here文档(内联输入)cat << EOF 这是多行 输入内容 EOF
高级重定向技巧
1. 重定向到多个地方
使用tee
命令:
ls -l | tee filelist.txt | less
2. 丢弃输出
重定向到/dev/null
:
noisy_command > /dev/null 2>&1
3. 文件描述符操作
-
复制文件描述符:
command 2>&1 # 将stderr重定向到stdout
-
自定义文件描述符:
exec 3> custom_output.txt echo "测试" >&3 exec 3>&- # 关闭
4. 进程替换
diff <(ls dir1) <(ls dir2)
常见使用场景
-
记录日志:
script.sh > script.log 2>&1
-
分离输出和错误:
command > output.log 2> error.log
-
创建空文件:
> newfile.txt
-
多行输入:
mail -s "主题" user@example.com << END 邮件内容 第二行 END
掌握这些重定向技巧可以大大提高在Linux命令行环境下的工作效率。