LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   [Bash] Counting files (http://www.linuxquestions.org/questions/programming-9/%5Bbash%5D-counting-files-752757/)

paul_l 09-04-2009 04:32 PM

[Bash] Counting files
 
I'm making a script that's supposed to do different things depending of how many files there is in a folder that starts with ref.

I've tried to do a count with this for-loop:
Code:

for file in $dir/ref*
do
                i=$((i+1))
done

It seems to work fine, as long as there is at least one file starting with ref in the folder. If there is none the loop runs once with the variable file as "$dir/ref*". Anybody got some suggestion on how I could avoid that? Alternative solutions are also welcome :)

Thanks a lot in advance!

nadroj 09-04-2009 04:52 PM

i havent done any linux scripting in quite a long time, but instead of using the hardcoded string "$dir/ref*", can you run a command and save the output? something like:
Code:

for file in `ls $dir/ref*`
i know this is possible in other shells, but the syntax may be different in bash, i dont remember.

edit: note that above ` are "backticks" not single quotes.

paul_l 09-04-2009 05:00 PM

Works like a charm. Thanks a lot!! :)

catkin 09-04-2009 05:03 PM

Try
Code:

shopt -nullglob
for file in $dir/ref*
do
                i=$((i+1))
done


colucix 09-04-2009 05:04 PM

Following the suggestion by nadroj above, you can use the ls command, but you don't really need a loop if you do something like:
Code:

ls $dir/ref* 2> /dev/null | wc -l
the 2> /dev/null part redirects the standard error to nothing, so that you don't get the message "ls: cannot access dirname/ref*: No such file or directory" in the terminal if ls does not find ref* files. To assign the result to a variable, just do command substitution:
Code:

nfiles=$(ls $dir/ref* 2> /dev/null | wc -l)


All times are GMT -5. The time now is 07:36 AM.