Ubuntu – Measure every single command within a bash file

bashcommand linetime

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.

Best Answer

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"

$ /usr/bin/time -f "%E %C" sleep 2.34
0:02.34 sleep 2.34

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 name time2script.

#!/bin/bash

string='/usr/bin/time -f "%E %C"'

while IFS= read -r line
do
 cmd=$(<<< "$line" sed -e 's/ *//'|cut -d ' ' -f1)
 command=$(which "$cmd")
 if [ "$command" != "" ]
 then
  printf '%s %s\n' "$string" "$line"
 else
  printf '%s\n' "$line"
 fi
done < "$1"

Using time2script on the example in the edited question:

$ ./time2script socrates1
#!/bin/bash

/usr/bin/time -f "%E %C" mv /path/to/file /other/path/
cd /other/path/
/usr/bin/time -f "%E %C" tar -xzf /other/path/file

Redirect to create a modified shellscript,

./time2script socrates1 > socrates1-timing
Related Question