如何在不同文件中重定向 stdout 和 stderr

如何在不同文件中重定向 stdout 和 stderr

在运行 shell 脚本时,我们如何将 shell 脚本的输出重定向到两个不同的文件中。即STDOUT 和STDERR 文件。如果有一些错误日志应转到 STDERR 文件,如果脚本成功运行,则应在 STDOUT 文件下生成日志

答案1

尝试这个

echo "test" 1>STDOUT 2>STDERR

替换echo "test"为任何命令或脚本。

简单的例子

创建 script.sh 内容:

#!/bin/bash

du -shc /*

添加执行权限:

chmod u+x script.sh

并运行它:

./script.sh 1>STDOUT 2>STDERR

然后查看各个文件:

# cat STDOUT
8,6M    /bin
39M     /boot
0       /dev
4,1M    /etc
1,1G    /home
0       /initrd.img
0       /initrd.img.old
231M    /lib
4,0K    /lib64

# cat STDERR
du: cannot access `./proc/7422/task/7422/fd/4': No such file or directory
du: cannot access `./proc/7422/task/7422/fdinfo/4': No such file or directory
du: cannot access `./proc/7422/fd/4': No such file or directory
du: cannot access `./proc/7422/fdinfo/4': No such file or directory

要在脚本内设置重定向,请使用 exec

#!/bin/bash
exec 1>STDOUT 2>STDERR

du -shc /*

并简单地运行脚本:

./script.sh

解释:

1>filename
 Redirect stdout to file "filename."
1>>filename
 Redirect and append stdout to file "filename."
2>filename
 Redirect stderr to file "filename."
2>>filename
 Redirect and append stderr to file "filename."
&>filename
 Redirect both stdout and stderr to file "filename."
 This operator is now functional, as of Bash 4, final release.

M>N
 "M" is a file descriptor, which defaults to 1, if not explicitly set.
 "N" is a filename.
 File descriptor "M" is redirect to file "N."
M>&N
 "M" is a file descriptor, which defaults to 1, if not set.
 "N" is another file descriptor.

欲了解更多信息,请参阅输入/输出重定向

答案2

shell 脚本示例:

#!/bin/bash
echo "Good"
# and something bad I can't do under ordinary user
touch /root/something

运行为:

$ test.sh 1>/tmp/STDOUT 2>/tmp/STDERR

内容是:

$ cat /tmp/STDOUT 
Good
$ cat /tmp/STDERR 
touch: cannot touch '/root/something': Permission denied

相关内容