Linux 重定向

Linux 标准文件描述符
描述符  缩写 描述
0  STDIN  标准输入
1  STDOUT  标准输出
2  STDERR  标准错误
3-9    应该是扩展的标准输出(待验证)

命令行重定向

ls -al existfile notexitfile 1> outfile 2> errlog

解释

ls -al 这个命令不需要解释了
exitfile 配合前面的ls,列出 exitfile 文件的信息
notexitfile 配合前面的ls,列出 notexitfile 文件的信息
1> outfile 将标准输出放到 outfile 文件中,可以使用cat outfile 查看内容
2> errlog 将错误信息放到 errlog 文件中,可以使用 cat errlog 查看内容
脚本重定向 shell 中使用如下命令
echo "this is an error" >&2
echo "this is normal output"
解释
第一个echo,会将 this is an error 这句话输出到标准错误中
第二个,则是使用的系统默认,输出到标准输出中,也就是我们能在执行脚本的时候看到的内容。
如果将这个脚本保存为 test.sh,执行下面的命令
./test.sh 2> errlog

再使用

cat errlog

就可以看到 this is an error 这句话了。

如果在 test.sh 脚本中第一句增加如下脚本:

exec 2>errlog
直接执行 ./test.sh 命令,在errlog中也会看到内容。
如果在脚本中使用
exec 2>errlog

 这种形式,那么所有的错误都会输出到 errlog 中,可以使用

exec 2>&-

  命令取消这种重定向。

原文地址:https://www.cnblogs.com/cnyansen/p/3375978.html