0

I need a scipt that gets the prior month and writes it to a variable. After that I need to check if the month is a quarter month (Mar,Jun,Sep,Dec) and if it is call another script and pass the month year as an argument in the format "Sep-2020". If its not a quarter month call another script.

monthyear="Sep-2020"

if [[ quartermonth ]]
then runscript1 $monthyear
elif [[ not a quartermonth ]]
then runscript2 $monthyear
fi

3 Answers3

0

You can learn how to find previous month here

$monthyear="Sep-2020" //This wont work. Refer the above link 

if [[ $quartermonth % 3 -eq 0 ]] //quartermonth is the value of month taken from monthyear
then runscript1 $monthyear
elif [[ $quartermonth % 3 -ne 0]]
then runscript2 $monthyear
fi
0

bash should be available on oracle Linux; here's a bash version:

#!/bin/bash

lastmoyr=$(date '+%b-%Y' --date='1 month ago')
lm=$(date '+%m' --date='1 month ago')
lm=${lm#0}
echo last month-year "$lastmoyr"
echo last month number "$lm"

# Mar Jun Sep Dec ==> 3 6 9 12
if [[ $((lm % 3)) == 0 ]]; then
    runscript1 "$lastmoyr"
else
    runscript2 "$lastmoyr"
fi
Milag
  • 1,793
  • 2
  • 9
  • 8
0

I can't comment on the accepted answer, so'll write it as a new one.

Attention, the accepted answer will produce an unexpected result (the wrong month) in some cases, like if you run the script on 31th.

To illustrate, run this two examples on your bash shell (if your date utility doesn't support the needed options, let me know which one you're using and i'll try to adapt it).

:: From accepted answer (for simulated day 2020-October-31)

echo "Prior month? : $(date  '+%b-%Y' -d "$(date -d "2020-10-31") 1 month ago")"

Prior month? : Oct-2020 - "October", probably not what you want.

versus (a more reliable solution)

echo "Prior month? : $(date  '+%b-%Y' -d "$(date +%Y-%m-1 -d "2020-10-31") 1 month ago")"

Prior month? : Sep-2020 - "September" the correct prior month.

This happens because the date utility, for 'relative' calculations, for month usually uses 30 days and not "a month".

To work around this, you'll can calculate the prior month based on day 1 (or 15) instead of using the current day.

Adapting @Milag script, it would look something like.

#!/usr/bin/env bash

lastmoyr=$(date  '+%b-%Y' -d "$(date +%Y-%m-1) 1 month ago")
lm=$(date '+%-m' -d "$(date +%Y-%m-1) 1 month ago")
echo last month-year "$lastmoyr"
echo last month number "$lm"

# Mar Jun Sep Dec ==> 3 6 9 12
if [[ $((lm % 3)) == 0 ]]; then
    runscript1 "$lastmoyr"
else
    runscript2 "$lastmoyr"
fi
6ugr3
  • 411
  • 4
  • 7