bug-bash
[Top][All Lists]
Advanced

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

Re: Another mapfile question.


From: Steven W. Orr
Subject: Re: Another mapfile question.
Date: Fri, 05 Aug 2011 10:32:54 -0400
User-agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.18) Gecko/20110616 Thunderbird/3.1.11

On 8/5/2011 9:08 AM, Maarten Billemont wrote:
IFS=
aa=()
while read line
do
  aa+=("$line")
done<  fn

You should really put that IFS= on your 'read', so as not to break the default 
wordsplitting for the rest of your script:


For purposes of giving concise examples on this email list, I wrote it as above. In practice, something like the above construct that modifies IFS would be responsible for restoring IFS. e.g.,

old_IFS="$IFS"
# do stuff
IFS="$old_IFS"

More often, the code would be placed in a subroutine where IFS is declared as a local variable. Within that routine, if IFS needs to be restored, then old_IFS would also be locally declared. If IFS did not need to be restored (within the routine) then old_IFS might not even need to be declared.

One trick that bit me a while back, is that the order of declaring IFS and old_IFS is important. It has to be done in this order:

foo()
{
    typeset -r old_IFS="$IFS" # Must come first
    typeset IFS

    stuff...
}

This is because the initial value to old_IFS is referring to the outer scoped IFS. It is nice though that the locally declared IFS gets an initial value from the outer scope :-)

while IFS= read -r line

vs.
IFS=$'\n'
aa=($(<  fn))

Don't leave expansions unquoted!  you're still permitting pathname expansion 
here.

IFS=$'\n' read -rd '' -a aa<  <(fn)

vs.
mapfile -t aa<  fn

When compared to the above read, this will also read empty lines.  The read 
operation will merge multiple newlines into a single delimiter (as it does for 
all types of whitespace in IFS).

The while read works fine but is verbose.  The mapfile is a bit more concise.  
The read -a is fine and concise so long as you can live with the lack of empty 
lines.  I doubt mapfile is much use to you that while read doesn't already give 
you.


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



reply via email to

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