[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How use a local variable in for loop?
From: |
Eric Blake |
Subject: |
Re: How use a local variable in for loop? |
Date: |
Mon, 26 Jul 2010 19:57:18 -0600 |
User-agent: |
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.7) Gecko/20100720 Fedora/3.1.1-1.fc13 Lightning/1.0b2pre Mnenhy/0.8.3 Thunderbird/3.1.1 |
On 07/26/2010 07:50 PM, Peng Yu wrote:
> Hi,
>
> The variable f keeps the last value when the for loop is finished. Is
> there a way to declare it as a local variable, so that it disappears
> after for-loop is finished? (I could unset it, but I want to know if
> it can be a local variable)
>
> $ for f in a b; do echo $f; done
> a
> b
> $ echo $f
> b
Local variables can only be used in functions - ergo, the answer to your
question is to wrap the for loop in a function:
$ func () {
local f
for f; do
echo $f
done
}
$ f=1; func a b; echo $f
a
b
1
--
Eric Blake eblake@redhat.com +1-801-349-2682
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature