Shell – Date “1 month ago” not working in AIX

aixshell-script

In machine A (running Oracle Linux Server release 6.4), I am able to get the date of 1 month ago intelligently by using the following command:

$(date -d"1 month ago" '+%Y0%m')

But it is not working in machine B(AIX), is there an alternative way to achieve this? Both are in .sh files and run with:

sh Test.sh

Error shown in machine B:

date: illegal option -- d
Usage: date [-u] [+Field Descriptors]

Best Answer

It has nothing to do with the shell, but with the date command. The -d option is specific to the GNU implementation of the date command. On non-GNU systems, that won't work unless you install the GNU version of date as a separate package (that would probably be installed as gdate or as /opt/gnu/bin/date...).

Note that recent versions of ksh93 have a similar feature with their printf builtin command:

printf '%(%Y%m)T\n' '1 month ago'

(see also zsh for another shell with builtin date manipulation support (strftime builtin in the zsh/datetime module)).

Some other date implementations also have features to adjust dates. For instance, with BSD date, you could do:

date -v -1m +%Y%m

I'm not aware that AIX comes with a command that does date calculation and there is no command in the POSIX toolchest, so no standard/portable command for that. You could revert to perl or do the calculation by hand:

eval "$(date +'y=%Y m=%m')"
m=$((${m#0} - 1))
[ "$m" -gt 0 ] || m=12 y=$((y - 1)) # January case
printf '%d%02d\n' "$y" "$m"
Related Question