Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable to current date and date-1 in linux?

Tags:

date

linux

bash

I want to set the variable date-today to the current date, and date_dir to yesterday's date, both in the format yyyy-mm-dd.

I am doing this:

#!/bin/bash
d=`date +%y%m%d%H%M%S`
echo $d
like image 687
cloudbud Avatar asked Dec 10 '13 03:12

cloudbud


People also ask

How do you assign a date to a variable?

To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable. The most commonly used default value for a date variable is the function Getdate().

How do you assign a date to a variable in Unix?

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

How do I get the current date in YYYY MM DD format in Linux?

To format date in YYYY-MM-DD format, use the command date +%F or printf "%(%F)T\n" $EPOCHSECONDS . The %F option is an alias for %Y-%m-%d .


3 Answers

You can try:

#!/bin/bash
d=$(date +%Y-%m-%d)
echo "$d"

EDIT: Changed y to Y for 4 digit date as per QuantumFool's comment.

like image 104
cloudbud Avatar answered Oct 23 '22 04:10

cloudbud


You can also use the shorter format

From the man page:

%F     full date; same as %Y-%m-%d

Example:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)
like image 17
xloto Avatar answered Oct 23 '22 04:10

xloto


simple:

today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
like image 11
fraff Avatar answered Oct 23 '22 02:10

fraff