linux - for 循环和 while 循环遍历目录在 bash 中的工作方式不同

标签 linux bash shell scripting

我用两种不同的方式编写了一个脚本,如下所示。

#! /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 循环只是将它们分成两个目录。

Script comparison below

在我的例子中,它们都按预期工作,只是因为带有 while 循环的一个会打印消息“没有目录有测试文件”,即使它在任何目录中找到测试文件。

请帮助我理解这两个循环的工作方式有何不同。以下是输出(findtestfile 是上面左侧屏幕截图中的脚本):

enter image description here

最佳答案

避免使用像这样的循环

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/

相关文章:

java - 为什么 BufferedImage 输出看起来与 Linux 平台上 JFrame 窗口中的屏幕不同?

linux - 查找文件,转换并存储在同一个子目录中

shell - 用 shell 格式化数字

linux - 更改日期和时间系统后 Tomcat 卡住

php - CentOS 5.10 无法启用 php-openssl 扩展

linux - 如何运行一个 shell 来停止当前进程?

linux - ldap 用户的 nslcd 身份验证失败,错误为 "lookup failed: No results returned"

linux - shell脚本中的$SHELL破坏代码执行

python - curl 命令中文/日文 url 编码

git - .gitconfig 不遵循默认编辑器命令的 bash 别名?