Dileep
Dileep

Reputation: 136

`elif' unexpected.. for Date function

Here is my code

CURR_MNTH=$(date +'%m' -d 'now')

if [$CURR_MNTH < 04]
    THIS_QTR=1
elif [$CURR_MNTH < 07] && [$CURR_MNTH > 03]
    THIS_QTR=2
elif [$CURR_MNTH < 10] && [$CURR_MNTH > 07]
    THIS_QTR=3
elif [$CURR_MNTH > 09]
    THIS_QTR=4
fi

echo $THIS_QTR

I am trying to get the current quarter with the above logic, but the prompt says that i have `elif' unexpected error.. Can someone please help me

Upvotes: 2

Views: 150

Answers (2)

choroba
choroba

Reputation: 241758

You can get the quarter from the month by a formula:

THIS_QTR=$(( 1 + (10#$CURR_MNTH - 1) / 3))

The 10# prefix indicates decimal number, thus preventing the leading 0 to be interpreted as octal number indicator.

Upvotes: 3

Vadim Landa
Vadim Landa

Reputation: 2834

Provided that you use Bash, there are numerous errors:

  • no semicolons after the if statements;
  • no spaces between brackets and conditional expressions;
  • conjunctions should be given inside the same set of brackets;
  • consider using -lt and -gt for value tests.

The correct code would look like this:

CURR_MNTH=$(date +'%m' -d 'now')

if [[ $CURR_MNTH -lt 4 ]]; then
    THIS_QTR=1
elif [[ $CURR_MNTH -lt 7 && $CURR_MNTH -gt 3 ]]; then
    THIS_QTR=2
elif [[ $CURR_MNTH -lt 10 && $CURR_MNTH -gt 7 ]]; then
    THIS_QTR=3
elif [[ $CURR_MNTH -gt 9 ]]; then
    THIS_QTR=4
fi

echo $THIS_QTR

Consider running http://www.shellcheck.net/ on your code next time.

Upvotes: 6

Related Questions