Linux -/usr/bin/ time for bash scripts containing the & symbol

/usr/bin/ time for bash scripts containing the & symbol… here is a solution to the problem.

/usr/bin/ time for bash scripts containing the & symbol

Let’s say we have a bash script that contains commands, some of which can have & (&) symbols.
I wanted to use /usr/bin/time to measure the execution time of such a script, but the actual work is done in the background due to the symbols, and the script returns the command to the shell, resulting in a measurement result of zero

Is there a way to suppress the behavior of the WITH symbol (i.e. not letting the command run in the background)?

The reason I tried to do this

was because I wanted to do a massive benchmark (a large data set, as well as multiple tools (some of which exhibited this behavior)).

A concrete, very simple example is as follows.

Create a script test.sh contains:

#! /bin/sh
sleep 2 &

And try running it:

/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 is approximately 2 seconds (CPU or elapsed time).

Note that the script above is just a toy example. Also, assume that it cannot be modified (think of it as a black box).

Solution

Yes. Add a wait statement at the end of the script. This will cause the script to be “wait” to complete the background task.

Related Problems and Solutions