如何在 bash 中重新定义 stdout/stderr?
How can I redefine stdout/stderr in bash?
是否可以在 bash 中重新定义文件描述符(例如 stderr
)?
我想默认将所有输出发送到一个文件,同时仍然能够使用原始 stderr
和 stdout
。
#!/bin/bash
echo "Error: foo bar" 1>2
REAL_STDERR=2
REAL_STDOUT=1
2=open("/tmp/stderr.log")
1=open("/tmp/stdout.log")
echo "This goes to stdout.log"
if ! curl doesntexist.yet; then
echo "Error: Unable to reach host. See stderr.log for details" 1>REAL_STDERR
fi
exec
内置函数在没有为 运行 提供命令名称时执行此操作。
exec 3>&1 4>&2 2>/tmp/stderr.log >/tmp/stdout.log
echo "This goes to stdout.log"
echo "This goes to stderr.log" >&2
echo "This goes directly to real stderr" >&4
请注意,重定向是按照它们在命令行中从左到右给出的顺序进行处理的。因此,&1
和 &2
被同一命令上的任何先前重定向解释为已修改。
如果你想为你的文件描述符使用变量名(自动分配数字),你需要 bash 4.1 或更新版本。在那里,你可以做:
exec {real_stderr}>&2 {real_stdout}>&1 >stdout.log 2>stderr.log
echo "This goes stdout.log"
echo "This goes to stderr.log" >&2
echo "This goes to real stderr" >&$real_stderr
是否可以在 bash 中重新定义文件描述符(例如 stderr
)?
我想默认将所有输出发送到一个文件,同时仍然能够使用原始 stderr
和 stdout
。
#!/bin/bash
echo "Error: foo bar" 1>2
REAL_STDERR=2
REAL_STDOUT=1
2=open("/tmp/stderr.log")
1=open("/tmp/stdout.log")
echo "This goes to stdout.log"
if ! curl doesntexist.yet; then
echo "Error: Unable to reach host. See stderr.log for details" 1>REAL_STDERR
fi
exec
内置函数在没有为 运行 提供命令名称时执行此操作。
exec 3>&1 4>&2 2>/tmp/stderr.log >/tmp/stdout.log
echo "This goes to stdout.log"
echo "This goes to stderr.log" >&2
echo "This goes directly to real stderr" >&4
请注意,重定向是按照它们在命令行中从左到右给出的顺序进行处理的。因此,&1
和 &2
被同一命令上的任何先前重定向解释为已修改。
如果你想为你的文件描述符使用变量名(自动分配数字),你需要 bash 4.1 或更新版本。在那里,你可以做:
exec {real_stderr}>&2 {real_stdout}>&1 >stdout.log 2>stderr.log
echo "This goes stdout.log"
echo "This goes to stderr.log" >&2
echo "This goes to real stderr" >&$real_stderr