Lee Ames
Lee Ames

Reputation: 349

Get today's date minus one Year in Unix (AIX)

I need to find today's date and then subtract a year and format that date into the YYYY-MM-dd format.

I am able to accomplish this with a script I wrote, but apparently it is only compatible with bash. I need it to be compatible with AIX.

lastYear=`date +'%Y-%m-%d' -d 'last year'`
searchDate="$lastYear 00.00.00";
echo "Retrieving data start from $searchDate"
myquery="myquery >= '$searchDate'"

The result when run on an AIX machine is that it only passes the "00:00:00" part of the $searchDate, the date does not prefix before the time as I hoped. What is the safest way to write this for the most compatibility across Linux/Unix variations?

Thank you!

Upvotes: 1

Views: 2140

Answers (2)

Jagawag
Jagawag

Reputation: 76

Checkout Updated Section Below

Original Answer

Try this. It uses the -v flag to display the result of adjusting the current date by negative one year -1y

searchDate=$(date -v-1y +'%Y-%m-%d')
echo "Retrieving data start from $searchDate"
myquery="myquery >= '$searchDate'"

Here is the output:

Retrieving data start from 2017-06-21

Note: I did try to run the lines you provided above in a script file with a bash shebang, but ran into an illegal time format error and the output was 00:00:00. The script I provided above runs cleanly on my unix system.

Hope this helps. Good luck!


Updated Section

Visit ShellCheck.net

It's a nice resource for testing code compatibility between sh, bash, dash, and ksh(AIX's default) shells.

Identifying the Actual Issue

When I entered your code, it clearly identified syntax that is considered legacy and suggested how to fix it, and gave this link with an example and a great explanation. Here's the output:

lastYear=`date +'%Y-%m-%d' -d 'last year'`
          ^__Use $(..) instead of legacy `..`.

So, it looks like you might be able to use the code you wrote, by making one small change:

lastYear=$(date +'%Y-%m-%d' -d 'last year')


Note: This question already has an accepted answer, but I wanted to share this resource, because it may help others trouble-shoot shell compatibility issues like this in the future.

Upvotes: 1

pedz
pedz

Reputation: 2349

Why make it so complicated?

#!/bin/ksh

typeset -i year=$( date +%Y )
(( year -= 1 ))
typeset rest=$( date +%m-%d )
echo "${year}-${rest}"

This should work in any shell. If you use sh replace the

$( ... )

with back tics

` ... `

But for bash and ksh I use $( ... ) -- just personal preference.

Upvotes: 1

Related Questions