I need to write the time taken to execute this command in a txt file:
time ./program.exe
How can I do in bash script?
I try with >> time.txt but that doesn’t work (the output does not go to file and does go to the screen).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Getting
timeinbashto write to a file is hard work. It is abashbuilt-in command. (On Mac OS X, there’s an external command,/usr/bin/time, that does a similar job but with a different output format and less recalcitrance.)You need to use:
It writes to standard error (hence the
2>notation). However, if you don’t use the sub-shell (the parentheses), it doesn’t work; the output still comes to the screen.Alternatively, and without a sub-shell, you can use:
Note the space after the open brace and the semi-colon; both are necessary on a single line. The braces must appear where a command could appear, and must be standalone symbols. (If you struggle hard enough, you’ll come up with
...;}|somethingor...;}2>&1. Both of these identify the brace as a standalone symbol, though. If you try...;}xyz, the shell will (probably) fail to find a command called}xyz, though.)You would need to do something like:
The key change is to run the shell with the script coming from the argument to the
-coption; you can replaceshwith/bin/bashor an equivalent name. That should get around any ‘Syntax error’ issues. I’m not quite sure what triggers that error, though, so there may be a simpler and better way to deal with it. It’s also conceivable thatxterm‘s-eoption only takes a single string argument, in which case, I suppose you’d use:You can manual bash
xtermas well as I can.I’m not sure why you run the timed program in background mode, but that’s your problem, not mine. Similarly, the
sleep 2is not obviously necessary if thehold: truekeeps the terminal open.