Bash “while read loop” does not properly recognize

2019-09-16 02:29发布

问题:

This question already has an answer here:

  • bash variable interpolation separate variables by a hyphen or underscore 3 answers
  • Error in string Concatenation in Shell Scripting 3 answers

I am using MacBook pro terminal to execute a shell script. It loops through a text file and create filenames based on each line in the file.

#!/bin/bash

year=2010
list=list_test.txt

mydir=thisdir

i=1  # counter

while read line
do
    echo $i $line
    file1=`echo $mydir/file_$year_$line_test.tif`
    file2=`echo $mydir/file_$year_$line_test.tif`
    echo $file1 $file2 

    i=$(($i+1))

done < $list

However, the output is peculiar:

1 17019
thisdir/file_.tif thisdir/file_.tif
2 17029
thisdir/file_.tif thisdir/file_.tif
3 17039
thisdir/file_.tif thisdir/file_.tif

Within the loop, bash does not recognize some variables, like "year" which is a global, and "line" which is read from the text file. The text file is as below:

17019
17029
17039

Another script with exactly the same manner works very well. This is mysterious to me now.

Any help or comments are extremely appreciated! Thanks very much!

回答1:

_ is a valid character for an identifier, but you want to use it as a literal character in the file name. You need to use the full form of parameter expansion, ${x} instead of $x.

(Also, the command substitution isn't necessary.)

file1=$mydir/file_${year}_${line}_test.tif
file2=$mydir/file_${year}_${line}_test.tif