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.
Thanks!
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityUse 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).
$()
. Example : DATE=$(date --date '1 day ago' +%Y%m%d)
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#*:})))"
man date
. thedate
command allows you to format the outputman date
, and yesterday is: epoch - 86400 (seconds)