Avoiding date using printf

Other topics

Remarks:

Using printf -v foo '%(...)T' is identical to foo=$(date +'...') and saves a fork for the call to the external program date.

Get the current date

$ printf '%(%F)T\n'
2016-08-17

Set variable to current time

$ printf -v now '%(%T)T'
$ echo "$now"
12:42:47

Syntax:

  • printf '%(dateFmt)T' # dateFmt can be any format string that strftime recognizes
  • printf '%(dateFmt)T' -1 # -1 represents the current time (default for no argument)
  • printf '%(dateFmt)T' -2 # -2 represents the time the shell was invoked

Contributors

Topic Id: 5522

Example Ids: 19641,19642

This site is not affiliated with any of the contributors.