help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Array Expansion


From: J.B.
Subject: Re: [Help-bash] Array Expansion
Date: Mon, 26 Jun 2017 12:53:54 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.1.1

On 06/26/2017 06:41 AM, Greg Wooledge wrote:
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)

I see. Can you rewrite bash to work the way I'm using it in my script? Also, how long will it take you?

Seriously though, thanks for your bash wiki. I learned a lot from it and still use it as a reference guide. So, thanks to everyone that's contributed to it.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]