How to test age of an AWS instance in a shell script

Here's one way to test age of an AWS (Amazon Web Services) instance in a shell script. The process below does the following:

  • Uses ec2-describe-instances to get instance launch time from Amazon (requires EC2 API Tools)
  • Converts time stamp to syntax suitable for the date command, then uses that to convert AWS launch time to seconds since 1970 format
  • Gets current system time in seconds since 1970 format
  • Calculates instance age in seconds
  • Depending on age, displays it in seconds, hours or days

Function to get launch time from AWS, convert it to seconds and get current time in seconds:

  if [ -z $region ]; then
    echo "ERROR: $FUNCNAME() needs 'region' var, but it's undefined"
  elif [ -z $instance ]; then
    echo "ERROR: $FUNCNAME() needs 'instance' var, but it's undefined"
    LaunchTime=$(ec2-describe-instances --region $region $instance |
                 awk '/^INSTANCE/ {gsub("T"," ",$10); print$10}')
    if [ -z $LaunchTime ]; then
      echo "ERROR: $FUNCNAME() unable to determine 'LaunchTime'"
      LaunchTimeSec=$(date --date="$LaunchTime" +%s)
      CurrentTimeSec=$(date +%s)

Function to calculate age and determine how to display based on number of seconds:

  InstanceAge=$(( $CurrentTimeSec-$LaunchTimeSec ))
  if [ $InstanceAge -lt 60 ]; then
  elif [ $InstanceAge -gt 59 ] && [ $InstanceAge -lt 3600 ]; then
    Age="$(( $InstanceAge/60 ))m"
  elif [ $InstanceAge -gt 3599 ] && [ $InstanceAge -lt 86400 ]; then
    Age="$(( $InstanceAge/60/60 ))h"
    Age="$(( $InstanceAge/60/60/24 ))d"

Example of the above in action:

echo "instance $instance in $region is $Age old (launched $(date --date="$LaunchTime" +"%F %T %z"))"


instance i-3453aa06 in us-west-2 is 10h old (launched 2012-12-13 23:25:53 -0800)


  • 1. Neil replies at 6th February 2013, 2:48 am :

    It looks like GetAge is validating for $InstanceAge but it actually calculates that itself. Should it not be checking for $CurrentTimeSec and $LaunchTimeSec ?

  • 2. Alain Kelder replies at 9th February 2013, 2:18 pm :

    Thanks for point that out, Neil. Yeah, that didn’t make any sense. I’m using a different flow in my production script and clearly didn’t put much thought into making it work outside of that.

    Made a couple of small changes that should hopefully make it more sensible now — removed the nonsensical validation of $InstanceAge in GetAge() and instead validating $LaunchTime in GetTimes() since that’s a prerequisite for caclulating $CurrentTimeSec and $LaunchTimeSec.

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).