Linux Shell Script 'if' statement - quick question
Linux Shell Script 'if' statement - quick question
Author
Discussion

TheExcession

Original Poster:

11,669 posts

274 months

Wednesday 29th September 2004
quotequote all
In C/JAVA I'd write

if( ( $STARTYEAR == $STOPYEAR ) && ( $STARTMONTH == $STOPMONTH ) && ( $STARTDAY == STOPDAY ) )
{
// do stuff

}


is there a way of compounding the tests in shell scripting e.g.

if [ ( ( $STARTYEAR == $STOPYEAR ) && ( $STARTMONTH == $STOPMONTH ) && ( $STARTDAY == STOPDAY ) ) ]
then
# do stuff...
fi

Doesn't work - do I need a separate if[ ] for each equality test?

many thanks
Ex

jig

244 posts

263 months

Wednesday 29th September 2004
quotequote all
TheExcession said:
In C/JAVA I'd write

if( ( $STARTYEAR == $STOPYEAR ) && ( $STARTMONTH == $STOPMONTH ) && ( $STARTDAY == STOPDAY ) )
{
// do stuff

}


is there a way of compounding the tests in shell scripting


Ex, my 'C' is crap (and I'm assuming bourne sh here), but firstly, I think you've got the test wrong, should be:
if [ "$STARTYEAR" = "$STOPYEAR" ]; then
blah blah
fi

As for multiple tests:
if [ "$STARTYEAR" = "$STOPYEAR" ] && [ "$STARTMONTH" = "$STOPMONTH" ]; then
blah blah
fi

would work I think. Check the manpage for "test" for syntax.

Pigeon

18,535 posts

270 months

Wednesday 29th September 2004
quotequote all
You need to double up on the square brackets:

if [[ ( ( $STARTYEAR == $STOPYEAR ) && ( $STARTMONTH == $STOPMONTH ) && ( $STARTDAY == STOPDAY ) ) ]]
then
# do stuff...
fi

You don't strictly need the round brackets either.

mrwomble

9,631 posts

279 months

Wednesday 29th September 2004
quotequote all
The [ ... ] notation is just a shorthand for the 'test' command, so 'man test' should give you everything you need. Off the top of my head, what you've written looks OK except that the test for string equality is '=' not '=='. If you're comparing numbers, then it's '-eq' (ie [ $NUM1 -eq $NUM2 ])

Edit to say - that's with ksh, at least. Other shells may vary.

>> Edited by mrwomble on Wednesday 29th September 15:59

TheExcession

Original Poster:

11,669 posts

274 months

Wednesday 29th September 2004
quotequote all
Thanks guy's - I've sussed it

if [ "$STARTYEAR$STARTMONTH$STARTDAY" == "$STOPYEAR$STOPMONTH$STOPDAY" ]

I keep forgetting about replacements!

Damn powerfull this linux stuff

best
Ex

edit to say - well sussed it one way - Pigeon's stuff looks a bit more 'proper' tho

>> Edited by TheExcession on Wednesday 29th September 16:09