用于显示目录中的文件和目录数的Shell脚本

时间:2014-03-18 07:02:36

标签: bash shell unix find

我正在尝试编写一个脚本,告诉您给定目录中有多少文件和多少目录。

这是我编写过的脚本,但输出始终是"文件数是。"和"目录数量为。"

这是我的代码:

#!/bin/sh
if [ -d "$@" ]
then
find "$@" -type f | ls -l "$@" | wc -l | echo "Number of files is $@"
find "$@" -type d | ls -l "$@" | wc -l | echo "Number of directories is $@"
fi

2 个答案:

答案 0 :(得分:3)

您似乎很难理解管道是如何工作的。你原则上不能"使用"结果" (stdout)管道(左侧)作为管道右侧的变量,您需要使用并将其读入变量,例如

printf "line1\nline2\n" | while read line; do_stuff_with "${line}"; done

或者您需要使用命令替换(并且可选地将其分配给变量),例如

files=$(find "$1" -maxdepth 1 -type f -printf . | wc -c)

进一步说明:

  • $@扩展到所有位置参数,如果多个参数,[ -d "$@" ]将失败。
  • ls完全是多余的
  • find以递归方式工作,但我想您只想检查第一个目录级别,因此需要maxdepth参数
  • 这会打破奇怪的路径,换行可以通过告诉find为每个找到的目录/文件打印一个字符,然后计算字节而不是行
  • 来解决这个问题。

如果你真的不希望这是递归的,那么使用 globbing 来获得所需的结果可能会更容易:

$ cat t.sh
#!/bin/bash

for file in "${1-.}"/*; do
        [ -d "${file}" ] && ((directories++))
        [ -f "${file}" ] && ((files++))
done

echo "Number of files: ${files-0}"
echo "Number of directories: ${directories-0}"

$ ./t.sh
Number of files: 6
Number of directories: 1

$ ./t.sh /tmp
Number of files: 9
Number of directories: 3

您可能需要检查man test以调整链接以获得所需结果。

答案 1 :(得分:2)

你似乎对这里的管道感到困惑。

您希望在find ... | wc -l命令中扩展echo的输出。

因此,根据您想要完成的内容,您的脚本应该如下所示:

#!/bin/sh

if [ -d "$@" ]; then
    echo "Number of files is $(find "$@" -type f | wc -l)"
    echo "Number of directories is $(find "$@" -type d | wc -l)"
else
    echo "[ERROR]  Please provide a directory."
    exit 1
fi
相关问题