View Single Post
  #2   (View Single Post)  
Old 30th November 2008
J65nko J65nko is offline
Administrator
 
Join Date: May 2008
Location: Budel - the Netherlands
Posts: 4,131
Default

Surround the variable you want to test with quotation marks and use square brackets for testing:
Code:
#!/bin/sh

check="$1"
FILE=testfile
result=$( grep "$1" ${FILE} )

echo Fixed original version

if [ "$result" != "" ] ; then
    echo "$check found"
else
    echo "$check not found"
fi
A sample run with the -vx options
Code:
$ cat testfile         
the quick brown fox jumps over the lazy dog

$ sh -vx greptest "brown fox" 

#!/bin/sh

check="$1"
+ check=brown fox
FILE=testfile
+ FILE=testfile
result=$( grep "$1" ${FILE} )
+ grep brown fox testfile
+ result=the quick brown fox jumps over the lazy dog

echo Fixed original version
+ echo Fixed original version
Fixed original version

if [ "$result" != "" ] ; then
    echo "$check found"
else
    echo "$check not found"
fi
+ [ the quick brown fox jumps over the lazy dog !=  ]
+ echo brown fox found
brown fox found
The same but now without the quotation marks
Code:
if [ $result != "" ] ; then
    echo "$check found"
else
    echo "$check not found"
fi
+ [ the quick brown fox jumps over the lazy dog !=  ]
greptest[13]: [: quick: unexpected operator/operand
+ echo brown fox not found
brown fox not found
The shell complains about "quick" being an unexpected operator or operand. The shell uses spaces, tabs or newlines as field separator. It sees "the" and then "quick". But "quick" is not one of the operators defined in test(1). By embedding the variable within quotes you tell the shell not to separate the value of the variable but to treat it as one single unit.
__________________
You don't need to be a genius to debug a pf.conf firewall ruleset, you just need the guts to run tcpdump
Reply With Quote