Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash -1 year from date

Tags:

bash

shell

Year=`date '+%Y'`
RTRN1=$?

This returns the current date in the logs, however i want to return the year before, so instead of this returning 2017 i want 2016.

Any help appreciated! Thanks

like image 253
Matt Avatar asked Oct 19 '25 16:10

Matt


2 Answers

For GNU date utility: use -d (--date) option to adjust the date:

Year=$(date +%Y -d'1 year ago')

echo $Year
2016
like image 161
RomanPerekhrest Avatar answered Oct 21 '25 07:10

RomanPerekhrest


You can always capture the year with date +'%Y'. You can subtract 1 with the POSIX arithmetic operator, e.g.

$ echo $(($(date +%Y) - 1))
2016

You can also use the POSIX compliant expr math operators, e.g.

$ expr $(date +%Y) - 1
2016

(note: with expr you must leave a space between the math operator and the values)

The GNU date operator -d with '1 year ago' will work as specified in the comments and other answer, along with let dt=$(date +%Y)-1; echo $dt as specified in the other answer (no spaces allowed with let).

Of all the choices, if I didn't have GNU date, I'd pick the POSIX arithmetic operator $((...)) with a date command substitution minus 1.

like image 32
David C. Rankin Avatar answered Oct 21 '25 06:10

David C. Rankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!