扩展bash数组仅给出第一个元素

扩展bash数组仅给出第一个元素

本文介绍了扩展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数组仅给出第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:27