Bash “while read loop” does not properly recognize variables [duplicate]

若如初见. 提交于 2020-01-06 06:19:15

问题


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


来源:https://stackoverflow.com/questions/46305806/bash-while-read-loop-does-not-properly-recognize-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!