我用两种不同的方式编写了一个脚本,如下所示。
#! /bin/bash
chk=0
ls sid/. | while read dir #<--second script just has a for loop instead
do
if [ -e "sid/$dir/testfile" ]; then
[ $chk -eq 0 ] && chk=1
echo "$dir|testfile"
fi
done
[ $chk -eq 0 ] && echo "No directory has testfile"
While 循环使我能够更好地控制之间有空格的目录。 For 循环只是将它们分成两个目录。
在我的例子中,它们都按预期工作,只是因为带有 while 循环的一个会打印消息“没有目录有测试文件”,即使它在任何目录中找到测试文件。
请帮助我理解这两个循环的工作方式有何不同。以下是输出(findtestfile 是上面左侧屏幕截图中的脚本):
最佳答案
避免使用像这样的循环
while IFS= read -r dir; do
echo "${dir}"
done < <(find sid -mindepth 1 -type d)
您可以使用以下方式寻找循环的替代方案
find sid -mindepth 2 -maxdepth 2 -name testfile -type f |
sed -r 's#sid/(.*)/(.*)#\1|\2#'
find sid -mindepth 2 -maxdepth 2 -name testfile -type f |
grep -q . || echo "No directory has testfile"
关于linux - for 循环和 while 循环遍历目录在 bash 中的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57160060/