Thursday, February 28, 2013

UNIX time command output redirect to file


As you know the 'time' command run programs and summarize system resource usage. Here is a way how you can redirect 'time' command output to file. I would recomend you to go through this page to understand more about 'time' command.

e.g. We are executing 'prog.sh' along with 'time' command.
$ time ./prog.sh 
Initiating merge
Merge completed

real	0m8.803s
user	0m0.010s
sys	0m0.000s
#Trying to redirect the output to a file
$ time ./prog.sh > out.txt

real	0m8.804s
user	0m0.020s
sys	0m0.000s
#out.txt content:
$ cat out.txt 
Initiating merge
Merge completed
#So it only redirected the STDOUT of the script executed, but the 'time' command outut is not redirected.
#This is becuase the command time sends it's output to STDERR (instead of STDOUT)
#To capture output of 'time' command:
$ { time ./prog.sh ; } 2> out.txt
Initiating merge
Merge completed
#Now out.txt content:
$ cat out.txt 

real	0m8.303s
user	0m0.010s
sys	0m0.000s
#And to capture output of script as well as time command:
$ { time ./prog.sh ; } &> out.txt
#'out.txt' now has both the outputs.
$ cat out.txt 
Initiating merge
Merge completed

real	0m8.303s
user	0m0.020s
sys	0m0.000s
As I have mentioned in my earlier post on UNIX 'time' command, there's two types of time command available:
1) Shell's in-build time: Gives only scheduler information
2) /usr/bin/time: Gives more information, also allows formatting the output

The second (/usr/bin/time) one accepts output redirection without code block:
$ /usr/bin/time ./prog.sh &> newout.txt

$ cat newout.txt 
Initiating merge
Merge completed
0.00user 0.01system 0:08.30elapsed 0%CPU (0avgtext+0avgdata 5728maxresident)k
0inputs+8outputs (0major+719minor)pagefaults 0swaps
Related posts:
- UNIX redirect man pages to file
- Redirect UNIX top command output to file
- UNIX redirect both stderr and stdout to file
- Run UNIX bash loop with nohup command

No comments:

© Jadu Saikia www.UNIXCL.com