在过去的几天里,我一直在尝试优化一些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