我正在尝试从stdin读取文件列表,每个文件由换行符分隔,但是我注意到只有第一个元素被附加到列表中.我注意到这只是输入两个字符串然后q.有谁能解释为什么?
files=()
read input
while [ "$input" != "q" ] ;
do
files+=( "$input" )
read input
done
for f in $files ;
do
echo "the list of files is:"
echo "$f"
echo "The length of files is ${#files} " #prints 1, even if 2+ are entered
done
Run Code Online (Sandbox Code Playgroud)
实际上你的files+=( "$input" )表达式是在你的数组中添加元素,但你没有正确地迭代它.
你的最后一个循环应该是:
for f in "${files[@]}"; do
echo "element is: $f"
done
Run Code Online (Sandbox Code Playgroud)
$ a+=(1)
$ a+=("hello")
$ a+=(3)
$ for i in "${a[@]}"; do echo "$i"; done
1
hello
3
Run Code Online (Sandbox Code Playgroud)