2
# date +"%b %d %H:$(( $(date +'%M')-5))"
Nov 20 12:45
date +"%b %d %H:$(( $(date +'%M')-55))"
Nov 20 12:-5

Why I am getting -5 here? How to correct? Pls help.

0

1 Answer 1

6

Probably because you ran it at 12:50, where date +%M gives you 50 which becomes 45 when you subtract 5 and -5 if you subtract 55.

At 12:00, you would have gotten -5 with the first one as well.

At 12:07, you would have gotten 12:2 instead of 12:02 and at 12:09, some shells would complain that 09 is not a valid octal number. You can't just subtract 5 to the minutes field to get the time 5 minutes earlier. Consider that for instance at Jan 1 00:00, it should give you Dec 31 23:55.

For date calculation on Solaris, you can use perl or zsh though the latter is not always installed by default. To get the time it was 5 minutes ago:

perl -MPOSIX -le 'print strftime("%b %d %R", localtime(time - 5*60))'

or:

zsh -c 'zmodload zsh/datetime; strftime "%b %d %R" $((EPOCHSECONDS - 5*60))'

Actually since version 11 of Solaris, /bin/sh and /bin/ksh are actually ksh93, so you could also use ksh there (better not sh as while sh is currently implemented by ksh93, that could change in the future and the standard sh language doesn't have those features):

ksh -c 'printf "%(%b %d %R)T\n" "5 minutes ago"'

As indicated by @glennjackman in comments, if you have bash installed, you could also do:

bash -c 'printf -v t "%(%s)T" -1 && printf "%(%b %d %R)T\n" "$((t - 5*60))"'

(support for %s and a recent enough version of bash was added in release 11 of Solaris as well).

And while we're at piling more languages, if you have a TCL interpreter, such as expect:

expect -c 'puts [clock format [
  clock add [clock seconds] -5 minute] -format "%b %d %R"]'

Or python3:

python3 -c 'import time; print(time.strftime("%b %d %R", time.localtime(time.time() - 5*60)))'
4
  • and starting in bash 4.2, you can write printf '%(%b %d %H:%M)T\n' $(( $(printf '%(%s)T' -1) - 300 )) -- what version of bash ships with Solaris 11, if any? Commented Nov 20, 2020 at 14:50
  • @glennjackman, (only if $IFS doesn't contain digits as you forgot the quotes). Are you sure %s is supported on Solaris (as that's not a standard strftime() directive)? Commented Nov 20, 2020 at 15:07
  • I don't have access to a Solaris machine to verify. Commented Nov 20, 2020 at 15:08
  • 1
    @glennjackman, from the man page, looks like %s was added in Solaris 11 (The conversion specifications for %+, %P, %s, %OB, and %OV and also optional flag characters and optional field width were added in the Solaris 11 and OpenSolaris releases for a better compatibility with other operating systems). And it looks like Solaris 11 now comes with bash-4.4 (optional package like for zsh) Commented Nov 20, 2020 at 15:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .