Cris
Cris

Reputation: 128

Display month from number in bash script

I'm trying to show that if you type something for the month it displays the month such as january=1, february=2 , march=3 ...

and year 2012,2013,2014...

but if you type something greater than 12 for the month than it should tell you "sorry" and I can't figure out how to make the message work.

echo " please type a number for a month"
read month
echo " please type a number for a year"
read year

if [ "$month" = "1-12" ]
then
        cal "$month" "$year"
        sleep 2
        echo " thank you, good bye... "
else
        echo " sorry "  
        sleep 2
fi

Upvotes: 0

Views: 2148

Answers (4)

sorpigal
sorpigal

Reputation: 26096

How about

read -r -p 'please type a number for a month: ' month
read -r -p 'please type a number for a year: ' year
cal "$month" "$year" 2&>1 1>/dev/null && \
    { cal "$month" "$year" ; echo ' thank you, good bye... ' ; } || \
    echo ' sorry '
  • read can prompt for you, no need for echo
  • cal return status tells you whether it's going to work

Upvotes: 1

choroba
choroba

Reputation: 242038

To test the value just use logical and for two arithmetic conditions:

if (( month >= 1 )) && (( month <= 12 )) ; then
    cal $month $year
else
    echo Sorry.
fi

Upvotes: 0

bsravanin
bsravanin

Reputation: 1873

It is safer to allow cal to verify the integrity of the input.

cal $month $year 2>/dev/null
if [ $? -ne 0 ]; then
    echo sorry
fi

This will take care of inputs that are not integers as well.

Upvotes: 1

perreal
perreal

Reputation: 98088

if [[ $month -lt 13 && $month -gt 0  ]]  
then
        cal "$month" "$year"
        sleep 2
        echo " thank you, good bye... "
else
        echo " sorry "  
        sleep 2
fi

Upvotes: 1

Related Questions