Often times we need the current date (and time) when scripting inside bash or other shells. For example when creating a backup file or writing to a log.
Bash >= 4.2
In bash (>=4.2) it is best to use printf’s built-in date formatter (part of bash) rather than the external date (usually GNU date).
# Store current date as yyyy-mm-dd in $date
printf -v date '%(%Y-%m-%d)T'
# Store current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T'
# Remove -v to print directly
printf '%(%Y-%m-%d)T\n'
Bash < 4.2 and other shells
# Store current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# Store current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# Print current date
echo $(date '+%Y-%m-%d')