Saturday, October 29, 2022

[SOLVED] Expanding a bash array only gives the first element

Issue

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?


Solution

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


Answered By - janos
Answer Checked By - Marilyn (WPSolving Volunteer)