I tried using $(date)
in my bash shell script, however, I want the date in YYYY-MM-DD
format.
How do I get this?
Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...
We can use the `date` command to display or change the current date and time value of the system. We can print date and time value in different formats by using date command. We can also use this command for calculating date and time value-related tasks.
%D – Display date as mm/dd/yy. %Y – Year (e.g., 2020)
%D: Display date as mm/dd/yy. %h: Displays abbreviated month name (Jan to Dec). %b: Displays abbreviated month name (Jan to Dec). %B: Displays full month name(January to December). %m: Displays the month of year (01 to 12).
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date
(usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date # -1 -> explicit current date, bash >=4.3 defaults to current time if not provided # -2 -> start time for shell printf -v date '%(%Y-%m-%d)T\n' -1 # put current date as yyyy-mm-dd HH:MM:SS in $date printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 # to print directly remove -v flag, as such: printf '%(%Y-%m-%d)T\n' -1 # -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date date=$(date '+%Y-%m-%d') # put current date as yyyy-mm-dd HH:MM:SS in $date date=$(date '+%Y-%m-%d %H:%M:%S') # print current date directly echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
man date
Try: $(date +%F)
The %F
option is an alias for %Y-%m-%d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With