I'm running a C program from a Bash script, and running it through a command called time, which outputs some time statistics for the running of the algorithm.
If I were to perform the command
time $ALGORITHM $VALUE $FILENAME
It produces the output:
real 0m0.435s
user 0m0.430s
sys 0m0.003s
The values depending on the running of the algorithm
However, what I would like to be able to do is to take the 0.435 and assign it to a variable. I've read into awk a bit, enough to know that if I pipe the above command into awk, I should be able to grab the 0.435 and place it in a variable. But how do I do that?
Many thanks
You must be careful: there's the Bash builtin
time
and there's the external commandtime
, usually located in/usr/bin/time
(typetype -a time
to have all the availabletime
s on your system).If your shell is Bash, when you issue
you're calling the builtin
time
. You can't directly catch the output oftime
without some minor trickery. This is becausetime
doesn't want to interfere with possible redirections or pipes you'll perform, and that's a good thing.To get
time
output on standard out, you need:(grouping and redirection).
Now, about parsing the output: parsing the output of a command is usually a bad idea, especially when it's possible to do without. Fortunately, Bash's
time
command accepts a format string. From the manual:So, to fully achieve what you want:
As @glennjackman points out, if your command sends any messages to standard output and standard error, you must take care of that too. For that, some extra plumbing is necessary:
Source: BashFAQ032 on the wonderful Greg's wiki.
You can use this awk:
You could try the below awk command which uses split function to split the input based on
digit m
or lasts
.