Rajarshi Sarkar Rajarshi Sarkar - 3 months ago 9
Bash Question

Compare strings in shell script

I have a file named

parameters.txt
whose contents are as follows:

sheet_name:TEST
sheet_id:CST
sheet_access:YES


And I have a shell script which fetches this text from the
parameters.txt
file. It uses
:
as a delimiter for each line of the
parameters.txt
file and stores whatever is left of
:
in
var1
and whatever is right of
:
in
var2
. I want to print
matched
when
var1
stores
sheet_name
and
not matched
when it doesn't stores
sheet_name
. Following is my code which always prints
matched
irrespective of what
var1
stores:

filename=parameters.txt
IFS=$'\n' # make newlines the only separator

for j in `cat $filename`
do
var1=${j%:*} # stores text before :
var2=${j#*:} # stores text after :

if [ “$var1” == “sheet_name” ]; then
echo ‘matched’
else
echo “not matched“
fi

done


What am I doing wrong? Kindly help.

Answer

You have useless use of cat. But how about some [ shell parameter expansion ] ?

while read line
do
 if [[ "${line%:*}" = "sheet_name" ]] #double quote variables deals word splitting
 then
  echo "matched"
 fi
done<parameters.txt

would do exactly what you're looking for.


Message for you

[ ShellCheck ] says,

"To read lines rather than words, pipe/redirect to a 'while read' loop."


Check [ this ] note from shellcheck.