2

In a shell program, I would like to define a month variable within an if-statement as below. But I cannot seem to define a variable within the if-statement -- I keep geting an error message that says "command 'dmonth' not found." Any help will be much appreciated!

    #Enter date:

    echo "Enter close-out date of MONTHLY data (in the form mmdd): "
    read usedate
    echo " "

    #Extract first two digits of "usedate" to get the month number:

    dmonthn=${usedate:0:2}
    echo "month number = ${dmonthn}"
    echo " "

    #Translate the numeric month identifier into first three letters of month:

    if [ "$dmonthn" == "01" ]; then
        dmonth = 'Jan'
    elif [ "$dmonthn" == "02" ]; then 
        dmonth = "Feb" 
    elif [ "$dmonthn" == "03" ]; then 
        dmonth = "Mar" 
    elif [ "$dmonthn" == "04" ]; then 
        dmonth = "Apr" 
    elif [ "$dmonthn" == "05" ]; then 
        dmonth = "May" 
    elif [ "$dmonthn" == "06" ]; then 
        dmonth = "Jun" 
    elif [ "$dmonthn" == "07" ]; then
        dmonth = "Jul" 
    elif [ "$dmonthn" == "08" ]; then 
        dmonth = "Aug" 
    elif [ "$dmonthn" == "09" ]; then 
        dmonth = "Sep" 
    elif [ "$dmonthn" == "10" ]; then 
        dmonth = "Oct"
    elif [ "$dmonthn" == "11" ]; then 
        dmonth = "Nov"
    else 
        dmonth = "Dec" 
    fi

    echo dmonth

2 Answers 2

5

I think that you're having trouble with white space ... it's significant in Bourne shell and it's dirivitives. dmonth="Dec" is an assignment, wheres dmonth = "Dec" is a command with '=' and 'Dec' as arguments.

Sign up to request clarification or add additional context in comments.

Comments

2

As shellcheck would tell you, you can't use spaces around the = in assignments.

Instead of dmonth = 'Jan', use dmonth='Jan'.

To make the code prettier, you could use an array and index it:

dmonthn=09
months=( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec )
dmonth=${months[$((10#$dmonthn-1))]}
echo "$dmonth"

or a case statement:

case $dmonthn in
  01) dmonth='Jan' ;;
  02) dmonth='Feb' ;;
  03) dmonth='Mar' ;;
  ...
esac

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.