使用bash遍历文件(和目录)名称 [英] Iterating over file (and directory) names with bash
问题描述
我试图编写一个bash脚本来计算本地目录的文件数和目录数.这是我的第一次尝试:
I was trying to write a bash script for counting the number of files and the number of directories of the local directory. This was my first try:
#!/bin/bash
files=0
dir=0
for file in `ls`
do
if [ -d $file ]
then
dir=$(($dir+1))
else
files=$(($files+1))
fi
done
echo "files=$files, direcotries=$dir"
但是,for
命令没有像我期望的那样遍历文件和目录的名称.如果文件ou目录的名称中包含空格,则无法正常工作.如果名称中有空格,则变量"file"将假定文件(或目录)名称中每个单词的值.
However, the for
command is not iterating over the names of files and directories as I would expect. If the name of the file ou directory has spaces, this does not work well. When there are spaces in the names, the variable "file" assumes the value of each of the words in the file (or directory) name.
有什么办法吗?
推荐答案
使用通配符:for file in *; do …; done
.这样可以使名称中的空格保持正确.还要考虑 shopt -s nullglob
.您的代码和我的建议都没有列出以点.
开头的名称.
Use a wild card: for file in *; do …; done
. That keeps the spaces in the names correct. Consider shopt -s nullglob
too. Neither your code nor my suggestion lists names starting with a dot .
.
此外,将if [ -d "$file" ]
用双引号括住变量值,以避免出现间距问题.
Also, use if [ -d "$file" ]
with double quotes around the variable value to avoid spacing problems.
因此:
#!/bin/bash
shopt -s nullglob
files=0
dir=0
for file in *
do
if [ -d "$file" ]
then
dir=$(($dir+1))
else
files=$(($files+1))
fi
done
echo "files=$files, directories=$dir"
在Bash中,还有其他写算法的方法,例如((files++))
.
In Bash, there are also other ways of writing the arithmetic, such as ((files++))
.
这篇关于使用bash遍历文件(和目录)名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!