Search code examples
bashdatedate-arithmetic

Getting previous month in shell script


Right now, I'm using the following line of code to use my shell script to get the previous month as a two digit number:

lastMonth=$(date -d 'last month' +%m)

However, I'm wondering what this will return if I run it in January. I want to get 12 back for December, but I'm having a hard time testing how this will behave when I run the script in January. Anyway I can test this?


Solution

  • You can use a ternary like structure for doing it because you need to manage only one particular case that you already know (when lastMonth = 01)

    lastMonth=$(date +%m)
    [ $lastMonth -eq "01" ] && lastMonth=12 || ((lastMonth--))
    

    First you need to test if you're in this special case with test-condition

    [ $lastMonth -eq "01" ] #return true if you're in January, else false
    

    Then the both control operators && (AND) and || (OR) are used like this

    If the test return true :

    [ true ] && lastMonth=12 || ((lastMonth--))
    

    lastMonth is set to 12 but not decremented because an OR condition need one of his both part to be true for manage, left part return true so it'll not evaluate his right part

    If the test return true :

    [ false ] && lastMonth=12 || ((lastMonth--))
    

    Right part of the AND will not be evaluated thanks to the lazy evaluation and execute directly right part of the OR condition, so decrement lastMonth in normal case

    This is just one way to do it, like with if statements, numerical manipulation and so on.