Shell: current date in a custom format
Get the current date and time into a bash variable with printf (bash 4.2 and later) or with the date command (older versions).
How to get the current date and time into a bash variable in a chosen format: with printf for bash 4.2 and later, with the date command for older versions.
With printf (bash 4.2 and later)
The -v option assigns the output to a variable instead of printing it. The %(...)T format is interpreted by printf, and the argument -1 stands for the current time (since bash 4.3, the argument can even be omitted).
# current date as yyyy-mm-dd in $date
printf -v date '%(%Y-%m-%d)T\n' -1
# current date and time as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# print the date directly, without a variable
printf '%(%Y-%m-%d)T\n' -1
With date (bash older than 4.2)
# current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# current date and time as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print the date directly
echo $(date '+%Y-%m-%d')
Notes
- The
\nin theprintf -vformat is part of the value:$datethen ends with a newline. Remove it from the format if the value must be used as is. - More on
printf -v: What does printf -v do? (Stack Overflow)