Shell scripts: variable assignment within read loops

CyberLeo Kitsana cyberleo at cyberleo.net
Tue Aug 19 19:34:14 UTC 2008


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 at CyberLeo.Net>

Furry Peace! - http://wwww.fur.com/peace/


More information about the freebsd-questions mailing list