我正在尝试编写一个循环遍历文件夹及其子文件夹并打印文件的 bash 脚本。这部分正在工作,但我尝试将这部分置于 if 条件下,但似乎我无法..
我想要的是,每发现 10 个文件就休眠 10 秒,然后从剩下的位置重新开始(继续)..
这就是我所做的
#!/bin/bash
declare -i x=0
if (( $x < 10 )); then
find /myfolder -type f -maxdepth 5 | while read file; do
echo $file;
((x++))
echo $x;
done
else
echo "found 10";
sleep 10;
$x=0;
fi
Run Code Online (Sandbox Code Playgroud)
我会这样做:
\nwhile IFS= read -rd \'\' file; do\n printf \'%s\\n\' "$file"\n ((++i % 10)) || sleep 10\ndone < <(find /myfolder -maxdepth 5 -type f -print0)\nRun Code Online (Sandbox Code Playgroud)\n这使用进程替换、-print0、IFS= read -rd \'\'和printf来echo代替允许文件名中的所有合法字符。
重要的一行是
\n((++i % 10)) || sleep 10\nRun Code Online (Sandbox Code Playgroud)\n这将 1 添加到i,然后检查现在是否是 10 的倍数。由于当不是10 的倍数i时余数不为零,因此计算结果为 true(退出状态为 0),并且没有任何反应。当是10 的倍数时,变为,具有非零退出状态并被执行。i((++i % 10))i ((++i % 10))((0))sleep 10
为什么你的方法不起作用:
\n检查是否x小于 10 后,find | while ...; do ... done完全运行命令 \xe2\x80\x93 ,永远不会检查x命令 \xe2\x80\x93在完成之前