Bash – Get Timestamp

Background

Wanted to explore the depth of flexibility available via Bash to get the current timestamp without necessarily hard-coding the date-time format.

 

Code


#!/bin/bash
 
function getTimestamp()
{
  
    #declare a name reference
    #The name reference should reference the first parameter
    declare -n ts_=$1
     
    ts_=`date +"%Y%b%d_%H%M%p"`
 
}
 
function getTimestampUsingVariableFormat()
{
  
    #declare a name reference
    #The name reference should reference the first parameter
    declare -n ts_=$1
     
    declare formatMask="%Y%b%d_%H%M%p"
     
    ts_=`date +"$formatMask"`
 
 
}

function getTimestampUsingVariableFormatAndEval()
{
  
    #declare a name reference
    #The name reference should reference the first parameter
    declare -n ts_=$1
     
    declare formatMask="%Y%b%d_%H%M%p"
     
    declare formatTSDate=`date +"$formatMask"`
 
    ts_=$(eval "echo $formatTSDate")
 
}
  
TS1=''
TS2=''
TS3=''
  
#invoke function
#pass variable by reference

getTimestamp TS1

getTimestampUsingVariableFormat TS2
 
getTimestampUsingVariableFormatAndEval TS3

#display result
echo "Timestamp(\$TS1) is ${TS1}"
 
echo "Timestamp(\$TS2) is ${TS2}"

echo "Timestamp(\$TS3) is ${TS3}"

Output

 

Source Code

GitHub

Gist

GetTimeStamp.sh
Link

References

  1. In bash, can I lazy eval date
    Link

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