lets say we have a bash script containing commands, some of which can have ampersand (&) symbols.
I would like to measure the execution time of such a script using the /usr/bin/time, but because of the ampersands the actual work gets done in the background, while the script returns command to the shell, resulting in measurements equal to zero.
Is there a way to suppress the ampersand behaviour (i.e. not letting the commands be run in background)?
The reason why I'm trying to do this is because I want to do a large-scale benchmark (large amount of data sets, and more than several tools (some of which exhibit such behaviour)).
A concrete, very simple example would be as follows.
Create a script test.sh containing:
#! /bin/sh
sleep 2 &
And try running it with:
/usr/bin/time ./test.sh
The result is:
0.00user 0.00system 0:00.00elapsed 100%CPU (0avgtext+0avgdata 668maxresident)k
0inputs+0outputs (0major+219minor)pagefaults 0swaps
The expected result would be around 2 seconds (either cpu or elapsed time).
Please note that the script above is only a toy example. Also, suppose that it cannot be modified (look at it as a black box).
This is a combination of answers from Elliott Frisch and Gilles (in the comments), and is intended to sum things up.
The answer is to create a wrapper script wrapper.sh that looks like:
#! /bin/sh
. $*; wait
The . (source command) will force the job to be executed in the same shell and not in the background, and wait will wait for all subprocesses to finish.
This can now be run as:
/usr/bin/time ./wrapper.sh ./test.sh
Please note that using the source command prevents you from changing the interpreter in test.sh's shebang line.