• Uncategorized

About linux : Expanding-a-bash-array-only-gives-the-first-element

Question Detail

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?

Question Answer

$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[@]}"

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.