【问题标题】:Why doesn't counting files with "for file in $0/*; let i=$i+1; done" work?为什么用“for file in $0/*; let i=$i+1; done”计算文件不起作用?
【发布时间】:2017-06-26 03:32:18
【问题描述】:

我是 ShellScripting 的新手,并且有以下基于一个更简单的脚本创建的脚本,我想向它传递一个带有路径的参数来计数文件。找不到我的逻辑错误以使其正常工作,输出始终为“1”

#!/bin/bash

i=0

for file in $0/*
do
    let i=$i+1
done

echo $i

执行我使用的代码

sh scriptname.sh /path/to/folder/to/count/files 

【问题讨论】:

标签: shell terminal scripting


【解决方案1】:

$0 是调用脚本的名称(粗略地说,有几个与此处无关的例外情况)。第一个参数是 $1,因此您要在 glob 表达式中使用 $1

#!/bin/bash
i=0
for file in "$1"/*; do
    i=$(( i + 1 ))      ## $(( )) is POSIX-compliant arithmetic syntax; let is deprecated.
done

echo "$i"

也就是说,你可以更直接地得到这个数字:

#!/bin/bash
shopt -s nullglob   # allow globs to expand to an empty list
files=( "$1"/* )    # put list of files into an array
echo "${#files[@]}" # count the number of items in the array

...甚至:

#!/bin/sh
set -- "$1"/*                        # override $@ with the list of files matching the glob
if [ -e "$1" ] || [ -L "$1" ]; then  # if $1 exists, then it had matches
  echo "$#"                          # ...so emit their number.
else
  echo 0                             # otherwise, our result is 0.
fi

【讨论】:

  • 谢谢!它工作得很好,学习一些小东西是一个很好的评论:)
  • 请注意,在第一个中,我没有处理目录为空的情况——它将在那里返回 1,而后两个将返回 0(因为它们要么使用 nullglob-e / -L 的测试)。
【解决方案2】:

如果你想统计一个目录中的文件数量,你可以这样运行:

ls /path/to/folder/to/count/files | wc -l

【讨论】:

  • 这是一个使用参数的脚本的工作示例。供个人使用,我会使用它,但学院要求我提供脚本:(
猜你喜欢
  • 1970-01-01
  • 2013-07-15
  • 2016-10-16
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多