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

LinuxBashDate

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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.

Solution 2 - Linux

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)

Solution 3 - Linux

simple:

today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"

Solution 4 - Linux

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncloudbudView Question on Stackoverflow
Solution 1 - LinuxcloudbudView Answer on Stackoverflow
Solution 2 - LinuxxlotoView Answer on Stackoverflow
Solution 3 - LinuxfraffView Answer on Stackoverflow
Solution 4 - LinuxrayView Answer on Stackoverflow