57

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
ruakh
  • 156,364
  • 23
  • 244
  • 282
cloudbud
  • 2,226
  • 1
  • 16
  • 30
  • 3
    I'm confused how you managed to get stuck at the exact point that you did. You managed to retrieve the date using a specified format -- but not the format you want. You managed to save the output to a variable -- but not the variable you want. How did you manage to write the code under "I am doing this", and how come you can't do the little bit of extra work of tweaking it to what you need? – ruakh Dec 10 '13 at 04:10
  • 1
    @ruakh: actually it is not dispalaying the $d variable that is why and i am very new to this bash scripting – cloudbud Dec 10 '13 at 04:12
  • The script that you've posted *does* print `$d`. What makes you say that it doesn't? – ruakh Dec 10 '13 at 04:17
  • @ruakh: i have done it. thanks !!! i was missing the "$d" – cloudbud Dec 10 '13 at 04:18

4 Answers4

98

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.

Chris Seline
  • 6,672
  • 1
  • 13
  • 14
cloudbud
  • 2,226
  • 1
  • 16
  • 30
12

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)
xloto
  • 400
  • 3
  • 8
9

simple:

today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
fraff
  • 590
  • 4
  • 8
0

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday
ray
  • 3,529
  • 1
  • 15
  • 12
  • i want to set it to a variable how to do that. i am creating a bash script – cloudbud Dec 10 '13 at 04:08
  • i would also like to tell you that it is picking date +%Y-%m-%d `2013-12-09` date +%Y-%m-%d -d yesterday is picking `2013-12-09` – cloudbud Dec 10 '13 at 04:10