# Compare two strings, UNIX Shell Programming



## overmind (Mar 26, 2011)

I've tried to compare two strings in an if statement using unix shell in FreeBSD (/bin/sh) and is not working. I think the problem appear for lenghty strings.

What could be wrong with that:


```
if [ "$testFileLine" = "ASCII C++ program text, with CRLF line terminators" ] ; then
    echo $testFileLine
fi
```

In this example the script never enter the if statement even testFileLine var have the same value as right string.


----------



## kiyolee (Mar 26, 2011)

Have you checked if $testFileLine contains the line break at the end?


----------



## overmind (Mar 26, 2011)

I don't think I have line breaks.

There is the whole script:


```
#!/bin/sh

find ./ >files_list.txt
fileList="files_list.txt"
fileLine=" "

while [ 1 ]
do
read fileLine || break
testFileLine=`file $fileLine | cut -d":" -f2| tr -d "\n"`
if [ "$testFileLine" = "ASCII C++ program text, with CRLF line terminators" ] ; then
    echo "this is a C++ source code"
    echo $testFileLine
fi
done < $fileList
```

I've tried first witout piping to tr command. Also I've tried using tr with \r instead of \r.


----------



## aragon (Mar 26, 2011)

How about this instead?


```
#!/bin/sh

for f in $( find . -type f ); do
  if file ${f} |grep -q "ASCII C++ program text, with CRLF line terminators"; then
    echo "this is a C++ source code"
    echo ${f}
  fi
done
```


----------



## shitson (Mar 26, 2011)

I'd agree with aragon and say that grep for pattern matching is going to be a better way to tackle this.


----------



## overmind (Mar 26, 2011)

@aragon: thank you, that is more elegant and it works


----------



## aragon (Mar 27, 2011)

There's an even simpler way if you don't mind the original output of file(1).


```
#!/bin/sh

find . -type f -exec file {} \; |grep "ASCII C++ program text, with CRLF line terminators"
```


----------

