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?
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.
$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)
$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[@]}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With