存储在子shell中的变量
Variables stored in subshell
脚本正在从 .csv 文件中读取文本并将其作为变量存储在 subshell 中我相信,在那之后我想在 shell 中使用这些变量但它们是空白的,如何修改脚本使其始终记住这些变量?
INPUT=file.csv
IFS=','
while read line1
do
echo "this is $line1"
done < $INPUT
echo "test $line1"
您脚本中的 while
不 在子 shell 中工作。变量
line1
刚退出循环就会为空,因为read
遇到
end of file
,这是退出循环的条件。变量 line1
在那一刻被覆盖为空字符串。请尝试
以下脚本:
INPUT=file.csv
IFS=','
while read -r line1
do
echo "this is $line1"
break
done < "$INPUT"
echo "test $line1"
然后你会看到变量$line1
保存着第一行的值
在输入文件中。
如果要保留 $line1
的值,请分配另一个变量
在循环中:
INPUT=file.csv
IFS=','
while read -r line1
do
echo "this is $line1"
line=$line1
done < $INPUT
echo "test1 $line1"
echo "test2 $line"
顺便说一句,IFS
将无法拆分行,因为您只放置了一个变量。如果你想把这条线分成
多个变量,请尝试:
while IFS=, read -r col1 col2 ..
或
while IFS=, read -r -a ary
取决于目的。
脚本正在从 .csv 文件中读取文本并将其作为变量存储在 subshell 中我相信,在那之后我想在 shell 中使用这些变量但它们是空白的,如何修改脚本使其始终记住这些变量?
INPUT=file.csv
IFS=','
while read line1
do
echo "this is $line1"
done < $INPUT
echo "test $line1"
您脚本中的 while
不 在子 shell 中工作。变量
line1
刚退出循环就会为空,因为read
遇到
end of file
,这是退出循环的条件。变量 line1
在那一刻被覆盖为空字符串。请尝试
以下脚本:
INPUT=file.csv
IFS=','
while read -r line1
do
echo "this is $line1"
break
done < "$INPUT"
echo "test $line1"
然后你会看到变量$line1
保存着第一行的值
在输入文件中。
如果要保留 $line1
的值,请分配另一个变量
在循环中:
INPUT=file.csv
IFS=','
while read -r line1
do
echo "this is $line1"
line=$line1
done < $INPUT
echo "test1 $line1"
echo "test2 $line"
顺便说一句,IFS
将无法拆分行,因为您只放置了一个变量。如果你想把这条线分成
多个变量,请尝试:
while IFS=, read -r col1 col2 ..
或
while IFS=, read -r -a ary
取决于目的。