如何在shell脚本中获取子进程和后代进程的执行时间?

时间:2014-02-17 02:19:54

标签: linux bash shell process fork

我想在后台运行test1.sh,test2.sh和test3.sh并分别记录执行时间。所以我使用了以下命令。

time `./test1.sh & ; wait` > record_1
time `./test2.sh & ; wait` > record_2
time `./test3.sh & ; wait` > record_3

虽然test1.sh中的内容可能会调用其他脚本:

./other_test1.sh &

所以test2.sh和test3.sh可以调用./other_test2.sh&和./other_test3.sh&

我想使用wait的原因是因为test1.sh和其他人将fork子进程,我希望执行时间包括子进程和后代进程的执行时间。但是它导致了如下错误:

bash: command substitution: line 1: syntax error near unexpected token `;'
bash: command substitution: line 1: `./test2 & ;wait'

我的想法是在后台部分等待命令将等待像test1.sh这样的后台脚本终止。我无法弄清楚语法出了什么问题。

2 个答案:

答案 0 :(得分:1)

由于&;都是分隔命令且具有相同优先级的列表运算符,因此不能将它们一起使用。这样做类似于使用多个条件列表运算符,如command1 && || command2。这是一个合乎逻辑的矛盾。

要解决这个可理解的约束,您可以使用带有(...)的子shell \继续该行。

time (./test1.sh & \ wait) &> record_1
time (./test2.sh & \ wait) &> record_2
time (./test3.sh & \ wait) &> record_3

答案 1 :(得分:0)

如果要测量test.sh的执行时间,则不需要

&; wait。此外,您无法仅使用>重定向时间输出。用这个: bash -c 'time ./test1.sh' &> record_1

所以你可以用以下几点来结束:

bash -c 'time ./test1.sh' &> record_1
bash -c 'time ./test2.sh' &> record_2
bash -c 'time ./test3.sh' &> record_3
相关问题