[Novalug] bash weirdness
Jon LaBadie
novalugml at jgcomp.com
Sat Apr 10 09:03:10 EDT 2010
On Fri, Apr 09, 2010 at 03:57:23PM -0400, Chris Snyder wrote:
> Can somebody please explain to me what this bash snippet is doing? Why is my
> array data disappearing outside of the 'while'? Bash doesn't have scoping by
> default unless you use local or something like that. WTF?!?
>
> thx
> Gopher.
>
> --------------------
> #!/bin/bash
>
> ls | while read output; do
> data[$i]="$output"
> let i++
> echo "Current array size: " ${#data[*]}
> done
>
> echo "Final array size" ${#data[*]}
>
As others have noted, bash runs control structures
redirected to or from pipes in a separate process.
Here are three other alternatives I've not seen mentioned.
1. Use ksh instead of bash.
2. Redirect from a subprocess
#!/bin/bash
while read output; do
data[$i]="$output"
let i++
echo "Current array size: " ${#data[*]}
done < <(ls)
echo "Final array size" ${#data[*]}
3. Redirect into a subprocess
#!/bin/bash
ls | {
while read output; do
data[$i]="$output"
let i++
echo "Current array size: " ${#data[*]}
done < <(ls)
echo "Final array size" ${#data[*]}
}
--
Jon H. LaBadie jon at jgcomp.com
JG Computing
12027 Creekbend Drive (703) 787-0884
Reston, VA 20194 (703) 787-0922 (fax)
More information about the Novalug
mailing list