get elapsed time in bash

Use the time since epoch to easily identify a span of time in a script

man date
%s     seconds since 1970-01-01 00:00:00 UTC
%N     nanoseconds (000000000..999999999)

.

start_time="$(date -u +%s)"
sleep 5
end_time="$(date -u +%s)"

elapsed="$(($end_time-$start_time))"
echo "Total of $elapsed seconds elapsed for process"

 Total of 5 seconds elapsed for process

Bash doesn't support floating point numbers, so you'll need to use a external tool like bc to compare times like 1475705058.042270582-1475705053.040524971

start_time="$(date -u +%s.%N)"
sleep 5
end_time="$(date -u +%s.%N)"

elapsed="$(bc <<<"$end_time-$start_time")"
echo "Total of $elapsed seconds elapsed for process"

 Total of 5.001884264 seconds elapsed for process

bash has a builtin timer variable

start=$SECONDS
# do stuff
end=$SECONDS
duration=$(( end - start ))
echo "stuff took $duration seconds to complete"

@jasonwryan already suggested it, but I'll throw it in as an answer as it is also my go-to when I want to time a script. To time myscript simply use:

time myscript

Tags:

Time

Bash

Date