2

I've the following sample script:

#!/usr/bin/env bash
sleep 5
printf "times cmd: "
times
printf "pipeline: "
times | ( read user sys; echo $user; )
printf "head: "
times | head -n1
printf "times cmd again: "
times

with the following output:

$ ./test.sh 
times cmd: 0m0.003s 0m0.005s
0m0.001s 0m0.001s
pipeline: 0m0.000s
head: 0m0.000s 0m0.000s
times cmd again: 0m0.003s 0m0.006s
0m0.003s 0m0.004s

Question is, why times command resets time when used with a pipeline? Is there any way to avoid it in order to parse the value?

3

Within a pipeline, all commands are run in a subshell. times reports time spent by the shell and its subshells, but not its parent shell.

You can try process substitution instead:

times > >( head -n1 )
times > >( read user sys ; echo $user )
0

It is a matter of which shell we are talking about.
On this shell, I get:

$ times
0m9.805s 0m3.372s
39m29.072s 0m15.537s

Because it has been running for a while.
However, a sub-shell will report zero:

$ ( times )
0m0.000s 0m0.000s
0m0.000s 0m0.000s

And, as a pipeline is executed in a sub-shell for each part of it:

$  sleep 10 | times
0m0.000s 0m0.000s
0m0.000s 0m0.000s

If you run the command above, you should see the times output immediately (as it does not depend on the pipe) and the shell prompt return 10 seconds latter.

Workaround?

Stay in "this" shell:

$ times > >(read user sys; echo "$user") 

Then, why do you need times? Could time or the more powerful /usr/bin/time work for you?

Use time:

$ TIMEFORMAT="%R;%U;%S"; time { sleep 1; }
1.001;0.000;0.000
$ TIMEFORMAT="%U"; time { sleep 1; }         #### If you only want user.
0.000

Enclose several process in braces:

$ time { wc /etc/hosts; sleep 2; }
 21 115 327 /etc/hosts

real    0m2.003s
user    0m0.000s
sys     0m0.000s

Use the more powerful external time (sadly it only works in external executable files):

$ /usr/bin/time wc /etc/hosts
 21 115 327 /etc/hosts
0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 534maxresident)k
0inputs+0outputs (0major+109minor)pagefaults 0swaps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.