[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: I think bash logic in a loop like : while [ condition] |read somevar
From: |
Greg Wooledge |
Subject: |
Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed. |
Date: |
Tue, 24 Dec 2013 07:37:53 -0500 |
User-agent: |
Mutt/1.4.2.3i |
On Mon, Dec 23, 2013 at 11:57:32PM +0100, rens wrote:
> ls -1 /usr/bin|head -10 |while read fname
> do
> cval=$(( cval +1 ))
> echo cval = $cval file = $fname
> done
> # one would think cval is now 10. but it is not, contrary to any other
> programming language........
>
> echo " after while: cval = $cval"
> _______________________________
>
> does not set the value of cval after exiting the while loop.
The pipe creates subshells, so your entire while loop is running in
a subshell (a child process). Changes to variables inside the loop
will not persist once the subshell terminates.
http://mywiki.wooledge.org/BashFAQ/024 explains the issue in more
detail, and provides alternatives.
I'm sorry that other people did not explain the issue usefully.
Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Pierre Gaston, 2013/12/24
Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed.,
Greg Wooledge <=
- Message not available
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Greg Wooledge, 2013/12/24
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Pierre Gaston, 2013/12/25
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Chet Ramey, 2013/12/26
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Suvayu Ali, 2013/12/30
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Chet Ramey, 2013/12/30
- Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Suvayu Ali, 2013/12/30
Message not available
Re: I think bash logic in a loop like : while [ condition] |read somevar is flawed., Linda Walsh, 2013/12/24