Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bourne Shell Variable Value Testing 1

Status
Not open for further replies.

Michael42

Programmer
Oct 8, 2001
1,454
US
Hello,

In a Bourne shell script in testing a string value I am getting erroneous results. The script below should output yellow but it outputs green instead.

What can you advise?

Code:
#!/bin/sh

COLOR="yellow"

if [ $COLOR -eq "green" ]
then
   echo "green"
else
   echo "yellow"
fi

Thanks,

Michael42
 
feherke,

Thanks very much to spelling this out.

Thanks,

Michael42
 
.... also get accustomed to the proper quoting:
Code:
if [ [COLOR=red]"[/color]$COLOR[COLOR=red]"[/color] = [COLOR=red]'[/color]green[COLOR=red]'[/color] ]

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Vlad

Re: "quoting"
Could you explain the difference between these:

if [ "$COLOR" = 'green' ]
if [ "$COLOR" = "green" ]

I've used the second example for years without knowing it was 'incorrect'. Seems to work fine. Why is the first better?
 
Why is the first better
Provided your string literal doesn't contains special shell characters, it's the same.
But the single quoting habit is safer when you know you don't want shell substitution.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
that's right. Your string green is a constant string with no parameter expansion. While you can use either double-quotes OR single-quote, it's a matter taste and how purist you want to be.

The question is: why using double-quote make the shell try to expand something that has no expansible parts?

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Hi

Good thought for optimization, vlad. I will remember it, when I will fall asleep while my script works.

100 character echoed 100000 times in 5.046s with double quotes and in 3.632s with single quotes. Not bad for such a simple movement.

Feherke.
 
I appreciate the education. I'll try to apply this in future scripts.

Thanks PHV and Vlad.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top