计数使用shell脚本文件和目录 [英] Count files and directories using shell script
问题描述
我学习bash脚本编程,并写了一个脚本来计数是作为参数提供的目录中的文件和目录。我有它的工作似乎很奇怪我的一种方式,我想知道是否有这样做的一个简单的方法。
我注释掉code,将工作,但离开它作为比较。我试图让为
-loop工作,而不是使用如果
语句里面来检测,如果在一个项目给定的位置是文件还是目录。
修改:我刚刚发现了评论code计数在给定的位置以及子目录中的所有文件和目录!有没有什么办法prevent这一点,仅计算给定位置的文件和目录?
#!/斌/庆典LOCATION = $ 1
FILECOUNT = 0
DIRCOUNT = 0如果[$#-lt1]
然后
回声用法:./test2.sh<&目录GT;
退出0
科幻#DIRS = $($找到LOCATION型D)
#FILES = $($找到LOCATION型的F)#for在$ DIRSÐ
#做
#DIRCOUNT = $ [$ DIRCOUNT + 1]
#done#for在$ FILES˚F
#做
#FILECOUNT = $ [$ FILECOUNT + 1]
#done在$位置项目
做
如果[-f$项目]
然后
FILECOUNT = $ [$ FILECOUNT + 1]
ELIF [-d$项目]
然后
DIRCOUNT = $ [$ DIRCOUNT + 1]
科幻
DONE回声文件数:$ FILECOUNT
回声目录数:$ DIRCOUNT
由于某种原因输出的为
-loop,无论在哪里我点的位置,总是返回:
文件数:0目录数:1
你不是遍历给定目录内的文件列表;添加 / *
在 $位置
。你的脚本应该是这样的:
...
在$位置项目/ *
做
...
由于指向的罗布麻,只需添加 / *
将只计算不以开头的文件
。这样做,你要做到以下几点:
...
在$位置/ * $位置项目/.*
做
...
I'm learning bash scripting and have written a script to count the files and directories in the directory that is supplied as argument. I have it working one way which seems odd to me and am wondering if there is a simpler way of doing it.
I have commented out the code that will work, but left it in as a comparison. I am trying to get the for
-loop working, instead using if
statements inside it to detect if an item in the given location is a file or a directory.
Edit: I just found out that the commented code counts all files and directories in the subdirectories of the given location as well! Is there any way to prevent this and just count the files and directories of the given location?
#!/bin/bash
LOCATION=$1
FILECOUNT=0
DIRCOUNT=0
if [ "$#" -lt "1" ]
then
echo "Usage: ./test2.sh <directory>"
exit 0
fi
#DIRS=$(find $LOCATION -type d)
#FILES=$(find $LOCATION -type f)
#for d in $DIRS
#do
# DIRCOUNT=$[$DIRCOUNT+1]
#done
#for f in $FILES
#do
# FILECOUNT=$[$FILECOUNT+1]
#done
for item in $LOCATION
do
if [ -f "$item" ]
then
FILECOUNT=$[$FILECOUNT+1]
elif [ -d "$item" ]
then
DIRCOUNT=$[$DIRCOUNT+1]
fi
done
echo "File count: " $FILECOUNT
echo "Directory count: " $DIRCOUNT
For some reason the output of the for
-loop, no matter where I point the location to, always returns:
File count: 0 , Directory count: 1
You're not iterating over the list of files inside the given directory; add /*
after $LOCATION
. Your script should look like:
...
for item in $LOCATION/*
do
...
As pointed by dogbane, just adding /*
will count only files that does not begin with .
; for doing so, you shall do the following:
...
for item in $LOCATION/* $LOCATION/.*
do
...
这篇关于计数使用shell脚本文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!