Bourne variable unset outside while()

Rick Miller vmiller at hostileadmin.com
Thu May 8 21:18:19 UTC 2014


Thanks, Polytropon & Matthew!


On Thu, May 8, 2014 at 4:54 PM, Polytropon <freebsd at edvax.de> wrote:

>
> You have identified the problem: With the | redirector, a subshell
> is started which populates ${labels}, but at the "higher" level
> ${labels} keeps its setting (in this case, implicit empty string).
>
> Here's a workaround, using awk:
>
>         #!/bin/sh
>
>         fs="freebsd-ufs gprootfs 1G
>         freebsd-swap gpswapfs 1G
>         freebsd-ufs gpvarfs 1G"
>
>         labels=`echo "${fs}" | awk '{printf("%s ", $2);}'`
>         echo "labels = ${labels}"
>
> In this example, with `...`, which is the same as $(...), also
> starts a subshell, but assigns its output to a variable, so there
> will be no scope problem. This idea uses the advantage that your
> delimiter is newline, and awk can process the input line per line,
> printing "incomplete lines" (no newline added) as output.
>
> The result will be:
>
>         labels = gprootfs gpswapfs gpvarfs
>
> Is this what you expected?
>

Wow!  It's soooo obvious to me now that you've pointed it out.  I don't
often use while read's in this manner.  Thanks for the feedback!

-- 
Take care
Rick Miller


More information about the freebsd-questions mailing list