Home > database >  BASH Modulus on Date switches
BASH Modulus on Date switches

Time:01-13

Here's my code

#!/bin/bash
#This works
MIN_SEQ_NO=$(date  %M)
echo "Minute" $MIN_SEQ_NO
MOD_VAL=$((MIN_SEQ_NO % 5))
echo "Minute Mod 5:" $MOD_VAL


#This works
DAY_SEQ_NO=$(date  %d)
echo "Day of Month:" $DAY_SEQ_NO
MOD_VAL=$((DAY_SEQ_NO % 5))
echo "Day of Month Mod 5:" $MOD_VAL

#But not this
DOY_SEQ_NO=$(date  %j)
echo "Day of Year " $DOY_SEQ_NO
MOD_VAL=$((DOY_SEQ_NO % 5))
echo "Day of Year Mod 5:" $MOD_VAL

Since today is the 12th, I'm expecting 2. How can I use bash modulus on date %j?

CodePudding user response:

012 in a math context is treated as an octal number because of the leading zero. The equivalent decimal expression is 10 % 5 and outputs 0.

You either have to strip the leading zero:

MOD_VAL=$(( ${DOY_SEQ_NO#0} % 5 ))

Or force decimal interpretation:

MOD_VAL=$(( 10#${DOY_SEQ_NO} % 5 ))
  • Related