[NTLUG:Discuss] Simple bash shell question

Ed Leach ntlug at levelofdetail.com
Fri Mar 30 16:14:53 CDT 2007


The line:

    for filename in $( ls -1 *.mpg )

will split a file name if it has a space in it.

See

    http://tinyurl.com/32wspa

Ed


. Daniel wrote:
> I found the culprit and a new/better way to do it.
> 
> As it turns out, doing the pipe thing forks another shell process and so 
> the scope of the variables is different.  So here's what I did to overcome 
> that:
> 
> ----
> #!/bin/sh
> fcount=0
> for filename in $( ls -1 *.mpg )
> do
>     fcount=$(expr $fcount + 1 )
>     echo $fcount
> done
> echo $fcount
> ----
> 
> It now behaves as I intended.  Eventually, this will become a Nautilus 
> script and I will replace "ls -1 *.mpg" with "echo 
> $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" to get a list of selected filename.  
> I need to count the filenames so I can then calculate a percentage value 
> for completion and pass it to zenity so I can have a progress meter dialog.
> 
> So, count first, then process, all the while echoing the progress values to 
> zenity so I can see how far along it has gone.  Crazy right?
> 
> 
>> . 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?
>>>
>>>
>> Daniel
>> It is obviously a scope issue - but to test this a little further, I set
>> the initial value to 2 and got the following results:
>> 3
>> 4
>> 5
>> 2
>> ... of course I only have 3 mpg files. No help perhaps.
>> Regards
>> Fred James
>>
>>
>> _______________________________________________
>> http://www.ntlug.org/mailman/listinfo/discuss
> 
> _________________________________________________________________
> 【お花見特集】日本全国のお花見スポットをご紹介。春爛漫、桜をめでに出かけよ
> う。 http://special.msn.co.jp/travelguide/hanami2007/index.htm 
> 
> 
> _______________________________________________
> http://www.ntlug.org/mailman/listinfo/discuss
> 



More information about the Discuss mailing list