Date: Tue, 19 Aug 2008 12:05:59 -0500 From: CyberLeo Kitsana <cyberleo@cyberleo.net> To: David Wolfskill <david@catwhisker.org>, freebsd-questions@freebsd.org Subject: Re: Shell scripts: variable assignment within read loops Message-ID: <48AAFD77.1080205@cyberleo.net> In-Reply-To: <20080818013328.GY44815@bunrab.catwhisker.org>
index | next in thread | previous in thread | raw e-mail
David Wolfskill wrote:
> foo=""
> cat $filename | while read bar ... ; do
> ...
> foo=$bar
> ...
> done
> echo $foo
>
A trick I've used to great advantage in bourne shell and bash for
passing multiple variables back is to produce small snippets of shell
script within a function, such as the following, for pulling in a bunch
of variables with a single program invocation for efficiency:
====
get_stats(){
stat -fc 'mount="%n" blksz="%S" total="%b" free_root="%f" \
free_user="%a"' "${@}"
}
get_stats "/" "/dev" "/tmp" | while read line
do
eval ${line}
# now mount, blksz, total, free_root, and free_user are set here.
printf "=> %s has %u free %u-byte blocks, out of %u\n" \
"${mount}" "${free_user}" "${blksz}" "${total}"
done
====
The function returns a series of lines that can be iterated with 'while
read', and evaluated individually for action. If the function returns
only a single line, it can be passed directly into eval:
====
eval $(get_stats "/")
====
As this shortcut does execute arbitrary code, however, there is always a
chance that it can be hijacked for nefarious purposes if the data source
is untrusted.
--
Fuzzy love,
-CyberLeo
Technical Administrator
CyberLeo.Net Webhosting
http://www.CyberLeo.Net
<CyberLeo@CyberLeo.Net>
Furry Peace! - http://wwww.fur.com/peace/
home |
help
Want to link to this message? Use this
URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?48AAFD77.1080205>
