27

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]} 

The output:

echo.sh
echo.sh read_output.sh

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

1

1 Answer 1

48

$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[@]}"
2
  • 4
    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). Commented Nov 19, 2017 at 1:13
  • 2
    If you're trying to expand the array into a string instead, shellcheck prefers "${files[*]}". stackoverflow.com/a/55149711/733092 Commented Jun 19, 2021 at 17:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.