I have the following file f1.txt:

A=\`expr $A + 1\`

and the following script file s1.sh

for line in $(cat testfile.txt)
   echo "$line"
   # eval $line
echo $A

When I run the script using "sh s1.sh" I get the following output:


I was expecting the output of the echo to be:

"A=`expr $A + 1`"

  1. I'd like to know why echo is putting newlines between the words?
  2. As well, when I uncomment the eval line I get the following error:

    s1.sh: eval: line 4: unexpected EOF while looking for matching ``'     
    s1.sh: eval: line 5: syntax error: unexpected end of file

I'd like to know what's wrong.

  1. Echo is putting newlines between words because it's splitting the input at the spaces, not at the newline.

  2. This is also why the eval doesn't work - it sees the first word, containing a ', and doesn't see the end of the line, which contains the closing '


Change the value of IFS (Internal Field Separator) to not contain spaces or tabs, but just newlines. You do it like this:


before you start reading in the file.


Don't use for loops for this. By default, as explained by @JennyD, your shell will split on whitespace and not keep the entire line. This is not the case if you read the file into a while loop instead of cat and for:

 $ while read line; do echo "$line"; done < f1.txt;
 A=`expr $A + 1`

This will also make the eval run correctly:

$ while read line; do eval "$line"; done < f1.txt; echo "A is $A"
A is 1

So, for example:

$ cat f1.txt 
A=\`expr $A + 1\`
$ while read line; do eval "$line"; done < f1.txt; echo "A is $A"
A is 6
  • If I change A=0 to A=5, I expected to $A to be 6 but $A is 1. In A=expr $A + 1, the $A is always 0. Why? – EggHead Jan 19 '14 at 15:11
  • @EggHead sounds like you're doing something wrong, it works fine here. See update. – terdon Jan 19 '14 at 15:14
  • Yes, I was using eval echo "$line" instead of eval "$line". It works now. Thx! – EggHead Jan 19 '14 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.