Bash:如何将输出定向到 stderr 和 stdout,以通过管道传输到另一个命令?
Bash: How to direct output to both stderr and to stdout, to pipe into another command?
我知道这个问题的变体已经被询问和回答 several times before,但我要么误解了解决方案,要么试图做一些古怪的事情。我的直觉是它不应该需要 tee
但也许我完全错了......
给出这样的命令:
sh
echo "hello"
我想将它发送到 STDERR 以便它可以在控制台上 logged/seen, 和 以便它可以发送到另一个命令。例如,如果我 运行:
sh
echo "hello" SOLUTION>&2 > myfile.txt
(SOLUTION>
就是我的问题的答案)
我要:
hello
将像任何其他 STDERR 消息一样显示在控制台中
- 文件
myfile.txt
包含 hello
tee
将 stdin 复制到其命令行上的文件,也复制到 stdout。
echo hello | tee myfile.txt >&2
这会将 hello
保存在 myfile.txt
中并将其打印到标准错误。
无需将其重定向至 stderr
。只需使用 tee
将其发送到文件,同时发送到 stdout
,这将转到终端。
echo "hello" | tee myfile.txt
如果您想将输出通过管道传输到另一个命令而不将其写入文件,那么您可以使用
echo "hello" | tee /dev/stderr | other_command
您还可以编写一个 shell 函数,它的作用相当于 tee /dev/stderr
:
$ tee_to_stderr() {
while read -r line; do
printf "%s\n" "$line";
printf "%s\n" "$line" >&2
done
}
$ echo "hello" | tee_to_stderr | wc
hello
1 1 6
这不适用于二进制输出,但由于您打算使用它在终端上显示文本,所以不必担心。
我知道这个问题的变体已经被询问和回答 several times before,但我要么误解了解决方案,要么试图做一些古怪的事情。我的直觉是它不应该需要 tee
但也许我完全错了......
给出这样的命令:
sh
echo "hello"
我想将它发送到 STDERR 以便它可以在控制台上 logged/seen, 和 以便它可以发送到另一个命令。例如,如果我 运行:
sh
echo "hello" SOLUTION>&2 > myfile.txt
(SOLUTION>
就是我的问题的答案)
我要:
hello
将像任何其他 STDERR 消息一样显示在控制台中- 文件
myfile.txt
包含hello
tee
将 stdin 复制到其命令行上的文件,也复制到 stdout。
echo hello | tee myfile.txt >&2
这会将 hello
保存在 myfile.txt
中并将其打印到标准错误。
无需将其重定向至 stderr
。只需使用 tee
将其发送到文件,同时发送到 stdout
,这将转到终端。
echo "hello" | tee myfile.txt
如果您想将输出通过管道传输到另一个命令而不将其写入文件,那么您可以使用
echo "hello" | tee /dev/stderr | other_command
您还可以编写一个 shell 函数,它的作用相当于 tee /dev/stderr
:
$ tee_to_stderr() {
while read -r line; do
printf "%s\n" "$line";
printf "%s\n" "$line" >&2
done
}
$ echo "hello" | tee_to_stderr | wc
hello
1 1 6
这不适用于二进制输出,但由于您打算使用它在终端上显示文本,所以不必担心。