0

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.

5
  • Don't use a for loop here; read mywiki.wooledge.org/BashFAQ/001 Commented Aug 11, 2016 at 12:58
  • 1
    You should run your code through shellcheck.net to catch a few issues. Also read Don't Read Lines with For and Bash FAQ 001 to see how to properly read line-by-line/field-by-field data. Commented Aug 11, 2016 at 12:58
  • 1
    Also your quotes are "smart"/unicode quotes and those aren't at all what you want in a shell script. Ensure you are using standard ASCII double and single quotes. Commented Aug 11, 2016 at 12:58
  • I just ran your script and sample file-- it works fine. You shouldn't use a for loop, but it does work. I have a feeling it's your parameters.txt that has an issue. Do a file parameters.txt and see what the output is. Commented Aug 11, 2016 at 13:08
  • That would be just reading line by line. I need to extract the left side of : for each line too. Commented Aug 11, 2016 at 13:34

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

How about this?

filename=parameters.txt

while IFS=: read -r first second; do 
  if [ “$first” == “sheet_name” ]; then 
     echo ‘matched’
  else  
     echo “not matched“ 
  fi 
done < $filename

1 Comment

Prints not matched for all cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.