在没有 wc 的情况下计算文件夹中的文件

Jam*_*272 3 shell bash pipe

为什么以下脚本给出的计数为 0 而不是给出目录中存在的文件计数?

#!/bin/bash
cd /root/Jamshed/script
count=0
ls -lrt > all_files
cat all_files | while read dir
do  
    count=$(($count + 1))
done
echo $count;
Run Code Online (Sandbox Code Playgroud)

dev*_*ull 6

它给出count零是因为您count在子外壳内递增。因此,对变量所做的更改丢失

而是说:

while read -r dir
do  
    count=$(($count + 1))
done < all_files
Run Code Online (Sandbox Code Playgroud)

以达到预期的效果。

也就是说,从不推荐解析ls