Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding a bash array only gives the first element

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?

like image 471
progonkpa Avatar asked Nov 18 '17 15:11

progonkpa


People also ask

Are bash arrays 1 indexed?

6.7 Arrays. Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.

What is the meaning of ${ 1 in bash?

$1 is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on. If you run ./script.sh filename1 dir1, then: $0 is the name of the script itself (script.sh)


1 Answers

$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[@]}"
like image 51
janos Avatar answered Sep 18 '22 05:09

janos