LamaEu LamaEu - 6 months ago 9
Bash Question

Comparing strings case-insensitively

I want to compare

Hello World
to
hello world
. The result should be true, as if they were equal. I'm doing:

while read line; do

newLine="$newLine$line"
done < $1

newp="Hello World"
if (( ${newp,,}==${newLine,,} )); then
echo "true"
else
echo "false"

fi


when I pass a text file consisting of:

#filename: file.txt

hello world


The output seems to be:

./testScript.txt: line 20: 0à»: hello world==hello world : syntax error in expression (error token is "world==hello world ")
+ echo false


What am I doing wrong here? Also, a bit unrelated, is there any way to pass the line that is in
file.txt
to a string(newLine) without doing that
while
I have done?

Answer

You should add commas and change the double parentheses to single brackets. The if statement should be something like:

if [ "${newp,,}" = "${newLine,,}" ]; then

And in relation to that while loop... It depends on what you want to do. If, like in this case, you want to get the entire file and save it as a single string, you could simply do:

line=$(cat $1)

I would suggest you only use that loop you wrote if you are trying to parse the file line by line, i.e. adding if statements, using different variables and so on. But for a simple case like this one, cat will do just fine.