扩展 bash 数组只给出第一个元素 [英] Expanding a bash array only gives the first element
本文介绍了扩展 bash 数组只给出第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想把当前目录的文件放在一个数组中,并用这个脚本回显每个文件:
I want to put the files of the current directory in an array and echo each file with this script:
#!/bin/bash
files=(*)
for file in $files
do
echo $file
done
# This demonstrates that the array in fact has more values from (*)
echo ${files[0]} ${files[1]}
echo done
输出:
echo.sh
echo.sh read_output.sh
done
有谁知道为什么在这个 for 循环中只打印第一个元素?
Does anyone know why only the first element is printed in this for loop?
推荐答案
$files
扩展到数组的第一个元素.试试 echo $files
,它只会打印数组的第一个元素.出于同样的原因,for 循环只打印一个元素.
$files
expands to the first element of the array.
Try echo $files
, it will only print the first element of the array.
The for loop prints only one element for the same reason.
要扩展到数组的所有元素,您需要编写为 ${files[@]}
.
To expand to all elements of the array you need to write as ${files[@]}
.
迭代 Bash 数组元素的正确方法:
The correct way to iterate over elements of a Bash array:
for file in "${files[@]}"
这篇关于扩展 bash 数组只给出第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文