Linux / Bash – Time Taken

Background

Need to determine how long a bash script task is taken.

Outline

  1. $SECONDS
    • Use $SECONDS
      • Issue $SECONDS and capture current time into variable
      • Perform task
      • Issue $SECONDS and capture time into second variable
      • Perform arithmetic
        • Subtract first variable from second variable
  2. Date Arithmetic
    • Capture date as epoch
      • $dtStarted = $(date +%s)
    • Perform Task
    • Capture new date as epoch
      • $dtCompleted = $(date +%s)
    • Perform arithmetic
      • Subtract first variable from second variable

Used $SECONDS

Code


#!/bin/bash

echo "Started at $(date)"

_dtStarted=$SECONDS

sleep 10

_dtCompleted=$SECONDS

_durationInSeconds=$((_dtCompleted - _dtStarted))

echo "Completed at $(date)"

echo "Time taken is $_durationInSeconds second(s)"

Output

$seconds.20181031.0855PM

Code


#!/bin/bash

_dtFormat="%Y-%m-%d %H:%M:%S %p"

_dtStarted=$(date +%s)
_dtStartedAsString=$(date +"$_dtFormat")

echo "Started ( as TS) $(date)"

echo "Started ( as String) :- $_dtStartedAsString"

echo ""
echo ""

sleep 10

_dtCompleted=$(date +%s)

_dtCompletedAsString=$(date +"$_dtFormat")

_durationInSeconds=$((_dtCompleted - _dtStarted))

echo "Completed ( as TS) $(date)"

echo "Completed (as String ):- $_dtCompletedAsString " 

echo ""
echo ""

echo "Time taken is $_durationInSeconds second(s)"

Output

timeDifferential.20181031.0851PM

 

Dedicated

Dedicated to learnshell.org.

Link

learnshell.org.20181031.0909PM

References

  1. Linux Commands
    • SECONDS
      • oreilly

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s