Unix:将stderr重定向到stdout

本文介绍了如何在Unix环境中将stderr重定向到stdout,特别是在执行包含多条命令的脚本时,如何确保错误输出能正确重定向,以便后续处理和分析。通过示例展示了在遇到"时间"命令时如何解决重定向问题。
摘要由CSDN通过智能技术生成

在过去的几天里,我一直在尝试优化一些Neo4j导入查询,作为执行脚本的一部分,我想将几​​个命令的输出重定向到一个文件中,以便稍后进行解析。

我从以下脚本开始,该脚本不对输出进行任何显式重定向:

#!/bin/sh
 
./neo4j-community-2.2.3/bin/neo4j start

现在让我们运行该脚本并将输出重定向到文件:

$ ./foo.sh > /tmp/output.txt
Unable to find any JVMs matching version "1.7".
 
$ cat /tmp/output.txt
Starting Neo4j Server...WARNING: not changing user
process [48230]... waiting for server to be ready.... OK.
http://localhost:7474/ is ready.

因此,有关找不到匹配的JVM的行将打印到stderr。 这很容易解决:

#!/bin/sh
 
./neo4j-community-2.2.3/bin/neo4j start 2>&1

让我们再次运行脚本:

$ ./foo.sh > /tmp/output.txt
 
$ cat /tmp/output.txt
Unable to find any JVMs matching version "1.7".
Starting Neo4j Server...WARNING: not changing user
process [47989]... waiting for server to be ready.... OK.
http://localhost:7474/ is ready.

太好了,按预期运作。 接下来,我扩展了脚本以停止Neo4j,删除所有数据,再次启动它并执行密码脚本:

#!/bin/sh
 
./neo4j-community-2.2.3/bin/neo4j start 2>&1
rm -rf neo4j-community-2.2.3/data/graph.db/
./neo4j-community-2.2.3/bin/neo4j start 2>&1
time ./neo4j-community-2.2.3/bin/neo4j-shell --file foo.cql 2>&1

让我们运行该脚本并重定向输出:

$ ./foo.sh > /tmp/output.txt
Unable to find any JVMs matching version "1.7".
 
real	0m0.604s
user	0m0.334s
sys	0m0.054s
 
$ cat /tmp/output.txt
Unable to find any JVMs matching version "1.7".
Another server-process is running with [50614], cannot start a new one. Exiting.
Unable to find any JVMs matching version "1.7".
Another server-process is running with [50614], cannot start a new one. Exiting.
+---------+
| "hello" |
+---------+
| "hello" |
+---------+
1 row
4 ms

似乎最后一行的stderr-> stdout重定向不起作用。 我的理解是,“时间”命令吞没了后面的所有参数,而我们希望此后再执行重定向。

我们可以通过将实际命令放入代码块并重定向其输出来解决此问题:

#!/bin/sh
 
./neo4j-community-2.2.3/bin/neo4j start 2>&1
rm -rf neo4j-community-2.2.3/data/graph.db/
./neo4j-community-2.2.3/bin/neo4j start 2>&1
{ time ./neo4j-community-2.2.3/bin/neo4j-shell --file foo.cql; } 2>&1
$ ./foo.sh  > /tmp/output.txt
 
$ cat /tmp/output.txt
Unable to find any JVMs matching version "1.7".
Another server-process is running with [50614], cannot start a new one. Exiting.
Unable to find any JVMs matching version "1.7".
Another server-process is running with [50614], cannot start a new one. Exiting.
Unable to find any JVMs matching version "1.7".
+---------+
| "hello" |
+---------+
| "hello" |
+---------+
1 row
4 ms
 
real	0m0.615s
user	0m0.316s
sys	0m0.050s

好多了!

翻译自: https://www.javacodegeeks.com/2015/08/unix-redirecting-stderr-to-stdout.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值