[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Array Expansion
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] Array Expansion |
Date: |
Mon, 26 Jun 2017 09:41:39 -0400 |
User-agent: |
Mutt/1.8.3 (2017-05-23) |
On Sun, Jun 25, 2017 at 12:25:32PM -0700, J.B. wrote:
> Expanding an array for use in a for-loop behaves differently depending on
> how the array was created.
No, it doesn't. You are simply not creating the array correctly.
There are only two ways to iterate over an array in bash: by value, or
by index.
By value: for f in "address@hidden"
By index: for i in "address@hidden"
> $ listoffiles=($(find ./path/ -type f -exec ls
> --quoting-style=shell-escape-always '{}' \;))
This is wrong. You are word-splitting the output of $(find) which is
never correct.
On Sun, Jun 25, 2017 at 10:17:57PM +0200, João Eiras wrote:
> This is most likely what you want:
>
> IFS=$'\x0a'
> listoffiles=( $(find ...) )
No, this also fails when filenames contain newlines.
Anything that relies on word-splitting is fragile.
There are a few correct ways to read output from find into a bash array.
Here are some of them:
mapfile -t -d '' files < <(find ... -print0) # requires bash 4.4
files=(); while IFS= read -r -d '' f; do
files+=("$f")
done < <(find ... -print0)
files=() i=0; while IFS= read -r -d '' f; do
files[i++]="$f"
done < <(find ... -print0)