21

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

The output:

echo.sh
echo.sh read_output.sh
done

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

that other guy
  • 109,738
  • 11
  • 156
  • 185
progonkpa
  • 2,981
  • 7
  • 25
  • 44

1 Answers1

34

$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.

To expand to all elements of the array you need to write as ${files[@]}.

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

for file in "${files[@]}"
janos
  • 115,756
  • 24
  • 210
  • 226
  • 3
    Note that the double-quotes should also be considered a necessary part of this idiom; without them, you can get weird effects from some characters in the array elements (spaces, wildcards, etc). – Gordon Davisson Nov 19 '17 at 01:13
  • If you're trying to expand the array into a string instead, shellcheck prefers `"${files[*]}"`. https://stackoverflow.com/a/55149711/733092 – Noumenon Jun 19 '21 at 17:05