Operating System - HP-UX
1843340 Members
2754 Online
110214 Solutions
New Discussion

Newbie script question...

 
SOLVED
Go to solution
Gene Laoyan
Super Advisor

Newbie script question...

OK, in VB there is an "If" statement that checks two variables then take action like so...
If var1="Dead" And var2="Live" then

'Do something...

ElseIf var1="Live" And var2="Dead" then

'Do something...

End If

How can I do that in a POSIX script?
4 REPLIES 4
john korterman
Honored Contributor
Solution

Re: Newbie script question...

Hi Gene,

you can try something like this:

$ cat decide.sh
#!/usr/bin/sh

if [[ ${1} = "Dead" && ${2} = "Alive" ]]
then
echo "${1} is Dead and ${2} is Alive"
elif [[ ${2} = "Dead" && ${1} = "Alive" ]]
then
echo "${1} is Alive and ${2} is Dead"
else
echo " neither nor..."
fi

And execute with two parameters, e.g.:
$ ./decide.sh Dead Alive

regards,
John K.
it would be nice if you always got a second chance
Peter Nikitka
Honored Contributor

Re: Newbie script question...

Hi,

another possibility would be a 'case' statement, which is easier to read, IMHO:

check="$var1"-"$var2" # use appropriate delimiter

Such use easily can check e.g. if 'at least one is alive':
case $check in
*Live*) echo Yeah ;;
esac

A complete check:
case $check in
Dead-Live) echo 1st;;
Live-Dead) echo 2nd ;;
Live-Live) echo both ;;
Dead-Dead) echo none ;;
esac

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
James R. Ferguson
Acclaimed Contributor

Re: Newbie script question...

Hi Gene:

In the shell, '-a' represents 'and' and '-o' signifies 'or'. Parenthesis used for logical grouping need to be escaped. The '!' operator denotes negation. The '&&' and '||' are often used to create compound expressions.

Have a look at the manpages for 'test' and for 'sh-posix'.

http://www.docs.hp.com/en/B2355-60127/test.1.html

http://www.docs.hp.com/en/B2355-60127/sh-posix.1.html

Consider:

# cat testit
#!/usr/bin/sh
if [ \( "$1" = "dead" -o "$1" = "expired" \) -a "$2" != "alive" ]; then
echo "it's very dead!"
fi

[ \( "$1" = "dead" -o "$1" = "expired" \) -a "$2" != "alive" ] && echo "dead!";

exit 0

# ./testit expired unsure
it's very dead!
dead!

Regards!

...JRF...
Gene Laoyan
Super Advisor

Re: Newbie script question...

All great answers and all worked. I used the example that john korterman gave because it was closer to what my simple mind can understand.

Thanks everyone!