Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YYYY-MM-DD format date in shell script

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format.
How do I get this?

like image 539
Kapsh Avatar asked Sep 09 '09 19:09

Kapsh


People also ask

How do I get current date in bash?

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 # ...

Which command is used for displaying date in the format dd mm yyyy in Unix?

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.

Which command will display the year from date command?

%D – Display date as mm/dd/yy. %Y – Year (e.g., 2020)

What is the command to show the date in Linux?

%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).


2 Answers

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 
like image 196
Philip Fourie Avatar answered Oct 04 '22 09:10

Philip Fourie


Try: $(date +%F)

The %F option is an alias for %Y-%m-%d

like image 37
kwatford Avatar answered Oct 04 '22 08:10

kwatford