Skip to main content
Tips

Print Execution Time of Shell Script in Linux

This quick tutorial teaches you how to display the execution time of a shell script in Linux.

Abhishek Prakash

Have you ever wondered how long did it take to run a certain shell script? You probably have already come across certain shell scripts that print the time to taken in running the script.

This information is useful some time for analysis specially if the scripts take some time to complete.

As a syadmin, if you create a script, you can display the execution time in the end as an additional information for the end user. This is one of the several ways you can make your shell scripts more interactive and more verbose.

Printing execution time of shell script

Get Execution Time Of Shell Script

Bash shell and a few other shells provide a built-in variable called SECONDS for this purpose. This variable keeps the number of seconds since a shell was opened and in case of script, it will be the seconds since script was run.

You can use the echo command in Linux to display the value of this SECONDS variable.

Let me show you a very simple sample script:

#!/bin/bash
sleep 5
sleep 7
echo "This script took $SECONDS seconds to execute"

I am using the bash sleep command in the above script that does nothing but waits for the specified time.

What do you think should be the output of the above script?

This script took 12 seconds to execute

See how easy it was to display the execution time of the script.

You can also use the time command to get the run time of the script.

time ./script.sh

The output for the above will be a little different from what you saw before. It will show the execution time in detail here. You can see that the execution time is 12.010 seconds, not 12 seconds.

real 0m12.010s
user 0m0.004s
sys 0m0.006s

I hope you liked this quick little Linux tip on displaying the execution time of a bash shell script. Would you use it in your scripts? What possible scenario you have in mind to use it?

Abhishek Prakash