System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

Error with script to compare two text strings

 
SOLVED
Go to solution

Error with script to compare two text strings

Dear Colleagues,

The script below tests to see if the value of the MONTH variable is "Jan". If so, it sets another variable called MON to 01 :
MONTH="Nov"
if test $MONTH="Jan"
then
MON=01
else MON=UNKNOWN
fi
echo "Month is $MONTH"
echo "Mon is $MON"

When I run this, I get :
Month is Nov
Mon is 01

I was expecting the value of Mon to be UNKNOWN but instead it is 01. In other words, the test condition in my if-statement is not working.
Does anyone know where this is going wrong?

Many thanks and regards,
Preet :-)
Nothing succeeds like excess
6 REPLIES 6
Kevin Bingham
Regular Advisor

Re: Error with script to compare two text strings

Hi Preet,

Try this

MONTH=`date|cut -d " " -f 2`
if [ $MONTH = "Jan" ]; then
MON=01
else MON=UNKNOWN
fi
echo "Month is $MONTH"
echo "Mon is $MON"

Solution

Re: Error with script to compare two text strings

The shell needs white space between operators to recognise them...

Change

if test $MONTH="Jan"

to

if test $MONTH = "Jan"

HTH

Duncan

Accept or Kudo
Santosh Nair_1
Honored Contributor

Re: Error with script to compare two text strings

Try putting a space around the equal size in the test statement, i.e.:

MONTH="Nov"
if test $MONTH = "Jan"
then
MON=01
else MON=UNKNOWN
fi
echo "Month is $MONTH"
echo "Mon is $MON"

Notice the space before and after the = in the 'if test' statement.

Hope this helps.

-Santosh
Life is what's happening while you're busy making other plans
Phil Daws_1
Occasional Visitor

Re: Error with script to compare two text strings

Use the following and cut the code down aswell ;)

MONTH="Nov"
MON=UNKNOWN
[ $MONTH = "Jan" ] && MON=01
Highlighted
Andreas Voss
Honored Contributor

Re: Error with script to compare two text strings

Hi,

you can also use a case construct:

case $MONTH in
Jan) MON=01;;
Feb) MON=02;;
Mar) MON=03;;
Apr) MON=04;;
May) MON=05;;
Jun) MON=06;;
Jul) MON=07;;
Aug) MON=08;;
Sep) MON=09;;
Oct) MON=10;;
Nov) MON=11;;
Dec) MON=12;;
*) MON=UNKNOWN;;
esac

Regards
Wodisch
Honored Contributor

Re: Error with script to compare two text strings

Hello Preet,

the reason is the missing spaces, as all the others already told you...
But as an additional tip:
ALWAYS quote substitutions, e.g.

if [ "$MONTH" = "Jan" ]
...
case "$MAONTH" in
...

for the simple reason that one day your variable might be unset or plain empty and then you will get an syntax error message from the shell - but with quotes your script will still work.

Just my ???0.02,
Wodisch