Is there a way to measure the time spent in every single command within a bash file? Hence, put time in front of every command. The quantity of commands is unknown right now, as I intend to use this time measure for future bash scripts, too. And also worth mentioning is that I intend to only run simple bash scripts having command1, command2, command3, ... etc. Hence, no complex higher logic scripts.
Lets say I have a bash file similar to this one:
#!/bin/bash
mv /path/to/file /other/path/
cd /other/path/
tar -xzf /other/path/file
Is there a way to get some output similar to this?
6.553s mv /path/to/file /other/path/
0.057s cd /other/path/
19.088s tar -xzf /other/path/file
I know that with time
I can get the time spent of a single command. But I am looking for a solution for measuring the time of every command itself.
You can use
/usr/bin/time
with the option-f
like the following example. Preceed each command in your shellscript with/usr/bin/time -f "%E %C"
See
man time
for more details.Example:
I made a small script, that can work to modify a simple shellscript by identifying commands, that can be tested with
/usr/bin/time
. Let us use the nametime2script
.Using
time2script
on the example in the edited question:Redirect to create a modified shellscript,
This is the naive approach. It has a few points of failure*, so I don't necessarily recommend using it, just wanted to mention it.
Example script foo.sh:
Example run:
* E.g.
eval
will choke on multi-line commands, like function declarations, array declarations, heredocs, even multi-line quotes. And commands that rely on the value of$0
may not work.