I am trying to do the following in a bash script: add all the device node files which don't start with /dev/sda
to an array called devices
. As the script will be executed on a read-only filesystem, I cannot use here documents.
Here is my code:
devices=()
ls -1 /dev/hd* /dev/sd* | while read -r device; do
if [[ "$device" != "/dev/sda"* ]]; then
devices+=($device)
fi
done
I don't understand why, at the end of the commands, devices
is still empty. For example, I can successfully print each item just by adding the command echo $device
before/after adding it to the array. But why don't they get added?
Also, if I run the same commands using here documents everything works fine:
devices=()
while read -r device; do
if [[ "$device" != "/dev/sda"* ]]; then
devices+=($device)
fi
done <<< $(ls -1 /dev/hd* /dev/sd*)
At the end of these commands the array devices
is correctly filled.
Can you help me understand why the first code extract doesn't work while the second one does? What am I doing wrong?