如何在 while read line
中读取变量?
例如:
the_list=$(..code..)
while read line
do
echo $line
done < $the_list
使用上面的代码会导致错误:
./copy.sh: line 25: $the_list: ambiguous redirect
如何在 while read line
中读取变量?
例如:
the_list=$(..code..)
while read line
do
echo $line
done < $the_list
使用上面的代码会导致错误:
./copy.sh: line 25: $the_list: ambiguous redirect
你可以写:
while IFS= read -r line
do
echo "$line"
done <<< "$the_list"
请参见§3.6.7 "Here Strings" in the Bash Reference Manual。
(为避免过多地操纵变量的内容,我还自作主张添加了一些双引号,并在read
中添加了-r
和IFS=
。)
如果您不在其他地方使用该变量,甚至可以省略它:
while read line ; do
echo $line
done < <( ... code ... )
your_code | while read line;
do
echo $line
done
如果您不介意在子shell中执行while循环(任何您修改的变量在done
之后将不可见于父进程)。
echo "${NAMES/,/$'\n'}" |while read -r NAME ;do TMP=${NAME#*_} ;TMP2=${TMP%_*_*_*_*_*} ;OUTPUT+=${TMP2/$'\n'/,} ;done
在循环后使用echo $OUTPUT
不会返回任何内容。 - Nikos Alexandriswhile read -r NAME; do TMP=${NAME#*_} ;TMP2="${TMP%_*_*_*_*_*}" ;if [ -z $OUTPUT ] ;then OUTPUT+=${TMP2:-$TMP2} ;else OUTPUT+=${OUTPUT:+,$TMP2} ;fi ;done <<< ${NAMES//,/$'\n'*}
循环遍历 NAMES=x_myd11a1_lst_night_2019_01_01T01_30_00,x_myd21a1_lst_night_2019_01_01T01_30_00
,得到 OUTPUT
变量 echo $OUTPUT
: myd11a1_lst_night,myd21a1_lst_night
。 - Nikos Alexandris脚本文件应该处于Linux模式。之前它是在dos模式下的。我使用dos2unix文件名
进行了更改。
e.g.:
dos2unix sshcopy.sh
现在它对我来说可以工作了。
IFS=
会将IFS设置为空字符吗?为什么在这种情况下需要它? - doubleDownIFS=
将$IFS
设置为空字符串(因此它不包含任何字符)。在这种情况下,由于只有一个字段,它的唯一作用是防止删除行首的 IFS 字符。 (要了解我的意思,请比较read foo <<< ' bar' ; echo "$foo"
和IFS= read foo <<< ' bar' ; echo "$foo"
。) - ruakh