[NTLUG:Discuss] Simple bash shell question
steve
sjbaker1 at airmail.net
Fri Mar 30 17:56:18 CDT 2007
. Daniel wrote:
> This is probably so elementary that maybe I shouldn't bother asking, but
> I'd like to know.
>
> Given the following:
> ----
> #!/bin/sh
> fcount=0
> ls -1 *.mpg | while read filename ; do
> fcount=$(expr $fcount + 1)
> echo $fcount
> done
> echo $fcount
> ----
>
> why do I get the following output?
> ----
> [daniel at alpha ~]$ test.sh
> 1
> 2
> 3
> 4
> 0
> ----
>
> I would expect:
> 1
> 2
> 3
> 4
> 4
>
> Where is my thinking broken?
It suggests that fcount is being worked on in an 'inner shell'
that's being invoked within the "while...done" part. Probably
because it's being piped into. The shell is a dark and arcane
thing to deal with sometimes!
But if you just want to count the number of mpg files then...
fcount=`ls -1 *.mpg | wc -l`
...would be quite a bit simpler.
More information about the Discuss
mailing list