Date: Fri, 09 May 2014 16:04:49 +0100 From: Arthur Chance <freebsd@qeng-ho.org> To: Polytropon <freebsd@edvax.de>, "Ivailo A. Tanusheff" <ITanusheff@postbank.bg> Cc: Rick Miller <vmiller@hostileadmin.com>, FreeBSD Questions <freebsd-questions@freebsd.org> Subject: Re: Bourne variable unset outside while() Message-ID: <536CEE91.7030202@qeng-ho.org> In-Reply-To: <20140509164546.d10312ee.freebsd@edvax.de> References: <CAHzLAVFhyPtkWCj1uj0aq0AusfrWL55UUn-mkxiyzUus7x4vdA@mail.gmail.com> <1422065A4E115F409E22C1EC9EDAFBA456552E@sofdc01exc02.postbank.bg> <20140509164546.d10312ee.freebsd@edvax.de>
next in thread | previous in thread | raw e-mail | index | archive | help
On 09/05/2014 15:45, Polytropon wrote: > On Fri, 9 May 2014 06:42:45 +0000, Ivailo A. Tanusheff wrote: >> Hi, >> >> I think you can check out this: >> http://stackoverflow.com/questions/7482510/variable-incrementing-in-bash >> >> So I sugest you do the same trick or use different approach - awk or something like this. > > This actually works (and is a good idea to get rid of my suggested > `awk ...` call per each line of input). In "here documents", variable > expansion can be used. If the input will be coming from a file > instead, using < /the/file can be done. > > #!/bin/sh > > fs="freebsd-ufs gprootfs 1G > freebsd-swap gpswapfs 1G > freebsd-ufs gpvarfs 1G" > > while read -r fstype fslabel fssize; do > labels="${labels} ${fslabel}" > done << EOF > "${fs}" > EOF > > echo "labels = ${labels}" > > The result is: > > labels = gprootfs gpswapfs gpvarfs > > There's a leading space because at the first addition, ${labels} > is empty, a space and the 1st entry are then added. The awk approach > didn't have that "bug", erm... feature. ;-) You can avoid that leading space by using yet another obscure bit of shell programming. Make the loop body labels="${labels}${labels:+ }${fslabel}" The variable expansion ${foo:+bar} is empty if ${foo} is empty or unset, and "bar" is ${foo} is set and non-empty. Also useful in things like somecmd ${outfile:+-o} ${outfile} args ...
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?536CEE91.7030202>