获取文件数量并遍历它们

Getting files quantity and traversing them

我正在尝试读取文件夹中的文件,然后对它们进行处理。所以我需要获取现有文件的数量,然后遍历它们。我这样做是为了获取数量,但后来它失败了。

#!/bin/sh
LIMIT=expr find . -maxdepth 1 -not -type d | wc -l;
i=1;
echo $LIMIT;
while [ "$i" -lt $LIMIT ]

Throws an error: ./converting.sh: 7: [: Illegal number: 

你觉得我错过了什么?任何类型的转换? 提前致谢,我不是 bash 脚本编写者,这让我发疯!

我可以提供不同的方法吗:

#!/bin/bash
FILES=/path/to/*
for f in $FILES
do
  echo "Processing $f file..."
  # take action on each file. $f store current file name
  cat "$f"
done

我认为您只需要一个简单的 for 循环并提前中断:

LIMIT=10
for f in ./*; do
    [[ -d $f ]] && continue
    ((++i == LIMIT)) && break
    ...
done

这就是您的代码出错的原因:您忘记使用命令替换语法。

LIMIT=expr find . -maxdepth 1 -not -type d | wc -l;

shell调用find命令,添加一个值为"expr"的变量LIMIT到find的环境中。 find|wc管道退出后,变量LIMIT不存在。你应该写

LIMIT=$(find . -maxdepth 1 -not -type d | wc -l)

继续你的代码,当你到达这一行时,你会得到一个错误:

while [ "$i" -lt $LIMIT ]

在这里,$LIMIT 没有被替换,所以 shell 看到 [ "$i" -lt ]。在我的系统上,/bin/sh 符号链接到 bash,我得到:

$ /bin/sh
sh-4.3$ i=10
sh-4.3$ unset LIMIT
sh-4.3$ if [ "$i" -lt $LIMIT ]; then echo Y; else echo N; fi
sh: [: 10: unary operator expected
N

"unary operator" 错误的结果是因为我只向 [ 命令传递了 2 个参数。对于 2 个参数,第一个参数应该是一个运算符,第二个参数应该是它的操作数。 10 不是 [ 命令已知的运算符。