I need to write a variable with "date" function and I need that the format is yyyymmdd (i.e. 20151031). Also I would remove a day (i.e. 20151031 becomes 20151030) I would use bash.


  • 2
    see man date. the date command allows you to format the output – Centimane Nov 3 '15 at 13:24
  • man date , and yesterday is: epoch - 86400 (seconds) – Olivier Dulac Nov 3 '15 at 13:34

Use date +%Y%m%d to print the current date.
Use date --date '1 day ago' +%Y%m%d to print yesterday's date (GNU's date).
Use date -v -1d +Y%m%d (FreeBSD).

  • Ok, but if I put it into a variable I get error #!/usr/bin/env bash DATE=date --date '1 day ago' +%Y%m%d gunzip -c /var/log/cisco/cisco.log-echo $DATE.gz > /var/log/cisco/file.log root@raspberrypi:/etc/my_scripts# date --date date: option '--date' requires an argument – Federi Nov 3 '15 at 13:56
  • You have to enclose your command into $(). Example : DATE=$(date --date '1 day ago' +%Y%m%d) – Vinz Nov 3 '15 at 13:59

bash-4.2 and above have built-in support for that (inspired from something similar in ksh93):

printf -v now '%(%s)T' -1
printf '%(%Y%m%d)T\n' "$((now - 86400))"

Would print yesterday's date (well, the date 86400 seconds ago) in YYYYMMDD format. It may not work if run at certain hours of the night at the time of winter/summer time switch (when days are 23 or 25 hours long).

It would probably be more reliable for those corner cases if written as:

printf -v now '%(%s:%H)T' -1
printf '%(%Y%m%d)T\n' "$((${now%:*} - 3600 * (12 + ${now#*:})))"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.