| |||||||||||
Count number of files Posted by hycheah (hycheah), 25 July 2007 I don't know what is wrong with this piece of code.It works fine when there is 1 or more .exe files in the directory. However, Count will still print Count: 1 even when there is no .exe file in the directory. #!sh count=0 for file in *.exe do count=`expr "$count" + 1` done echo "Count: $count" Posted by Chris_Isaac (Chris Isaac), 26 July 2007 I'm guessing here, but I think a DO loop will execute once even if the expression is false, you are adding 1 to $count so $count will always show 1 more than there should be, or at at least 1 as a minimum.I (again think) a while loop may solve your problems. Posted by george_Ball (george), 26 July 2007 It's more subtle than that... If you supply the shell with a wildcard expression and there are no files that match the expression, then the shell uses that expression as is... In other wordsecho *.exe will actually display *.exe if there are no files that match!! This is what is happening here, so there will always be one entry in the list so your loop will always execute once. The do...done is not a separate construct in the shell - it's tied to the "for" so the semantics are as you expect. You could modify your code to be count=0 for file in *.exe do if [ -e $file ] then count=`expr $count + 1` fi done which catches the pathological case you've described[i][/i] Posted by admin (Graham Ellis), 27 July 2007 Thanks, George (and welcome here!). I saw that question briefly and was scratching my head until you posted. Thanks!Posted by Chris_Isaac (Chris Isaac), 27 July 2007 yep...George... That was going to be my second guess This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |