The extension of the bash array gives only the first element

I want to put the files of the current directory into an array and display each file using 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

Output:

echo.sh
echo.sh read_output.sh
done

Does anyone know why only the first element is printed in this for loop?

+8
source share
1 answer

$filesexpands to the first element of the array. Try it echo $files, it will print only the first element of the array. The for loop prints only one item for the same reason.

To expand all elements of an array, you need to write how ${files[@]}.

The correct way to iterate over the elements of a Bash array:

for file in "${files[@]}"
+15
source

Source: https://habr.com/ru/post/1689503/


All Articles