使用来自(*)的文件的Bash for循环数组仅显示第一个元素

pro*_*kpa 8 linux bash scripting for-loop

我想将当前目录的文件放在一个数组中,并用这个脚本回显每个文件:

#!/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
Run Code Online (Sandbox Code Playgroud)

输出:

echo.sh
echo.sh read_output.sh
done
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么只有第一个元素在for循环中打印?

Sto*_*ica 15

$files扩展到数组的第一个元素.试试echo $files,它只会打印数组的第一个元素.由于同样的原因,for循环只打印一个元素.

要扩展到您需要编写的数组的所有元素${files[@]}.

迭代Bash数组元素的正确方法:

for file in "${files[@]}"
Run Code Online (Sandbox Code Playgroud)

  • 请注意,双引号也应视为此习语的必要部分;没有它们,您可能会从数组元素(空格、通配符等)中的某些字符中获得奇怪的效果。 (2认同)
  • 如果您尝试将数组扩展为字符串,shellcheck 更喜欢 `"${files[*]}"`。/sf/answers/3860479801/ (2认同)