1

I have the following file f1.txt:

A=0    
A=\`expr $A + 1\`

and the following script file s1.sh

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

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

A=0    
A=`expr      
$A     
+    
1`      

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.

2 Answers 2

2
  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 '

Solution:

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

IFS=$'\n'

before you start reading in the file.

0
1

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=0
 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=5    
A=\`expr $A + 1\`
$ while read line; do eval "$line"; done < f1.txt; echo "A is $A"
A is 6
3
  • 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
    Commented Jan 19, 2014 at 15:11
  • @EggHead sounds like you're doing something wrong, it works fine here. See update.
    – terdon
    Commented Jan 19, 2014 at 15:14
  • Yes, I was using eval echo "$line" instead of eval "$line". It works now. Thx!
    – EggHead
    Commented Jan 19, 2014 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .