I want to run an application and write (append) its processing time into a file. Also, I want to see the stdout and stderr output on the shell, but don't want to write it in a file. After running the process, I'd like to see time measured.
Since I'm on Bash, one solution would be this one, but it's pretty ugly, since tail needs to parse the whole output:
function run_time {
{ local TIMEFORMAT=%R; time "${@}"; } 2>&1 | tee /dev/stderr | tail -n 1 >> run_time.txt
}
Another variant would be to use GNU time:
function run_time {
/usr/bin/time --quiet --format '%e' --append --output=run_time.txt "${@}"
tail -n 1 run_time.txt
}
When running the function like this, the measured time gets written into the file, of course.
run_time mycommand > target.txt
A work-around would to redirect tail's output to stderr or a sub-shell:
run_time sh -c "exec mycommand > target.txt"
And here's my question: It there a more elegant way?
tailneeds to parse the whole file to find the last line. Sufficiently advanced versions will start at the end of the file, and seek backwards. As the comment forfile_lines()in GNU coreutils says, "Go backward through the file, reading 'BUFSIZ' bytes at a time (except probably the first), until we hit the start of the file or have readNUMBERnewlines." \$\endgroup\$