为什么不计算带有"的文件为$ 0 / *中的文件;让我= $ i + 1;完成"工作?

时间:2017-06-26 03:32:18

标签: shell terminal scripting

我是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 

2 个答案:

答案 0 :(得分: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)

如果要计算目录中的文件数,可以运行以下内容:

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