【问题标题】:Nesting a for loop in an if else statement在 if else 语句中嵌套 for 循环
【发布时间】:2012-01-26 19:12:15
【问题描述】:
if [ ! -f ./* ]; then
  for files in $(find . -maxdepth 1 -type f); do
    echo $files
else
  echo Nothing here
fi

返回

意外标记 `else' 附近的语法错误

对此很陌生。谁能指出我做错了什么?

【问题讨论】:

  • 我没有投反对票,但您的最后回声中有一个引用。
  • 请不要因为完全不同的问题而改变您的问题。您已经有 3 个答案解释您缺少“完成”。您的代码实际上没有多大意义。如果目录不存在,您想 cd 进入目录吗?为什么你期望读取文件的第一行会给你一个文件名?
  • @jordanm New to this. 让我放松一下。 nvr 直到昨天才编写 shell 脚本,因为我的老板需要在服务器上制作一个脚本,而最初执行它的人退出了。我在这里试试 =/
  • @Mechaflash 在学习一门新语言的同时为生产写一些东西很少有好的结果。在你写完符合规范的东西后,准备把它扔掉,并利用你学到的新知识把它做得更好。我的反对意见是为了改变问题,而不是你的代码质量。 mywiki.wooledge.org/BashGuide
  • 道歉。我会将问题恢复为原始形式并开始另一篇文章

标签: bash shell if-statement for-loop


【解决方案1】:

你忘了done

if [ ! -f ./* ]; then
  for files in $(find . -maxdepth 1 -type f); do
    echo $files
  done
else
  echo Nothing here
fi

【讨论】:

    【解决方案2】:

    你得到一个语法错误的原因是你没有用“done”语句结束循环。在这种情况下,您应该使用 while 循环而不是 for 循环,因为如果任何文件名包含空格或换行符,for 循环将中断。

    此外,如果 glob 扩展到多个文件,您发出的测试命令也会给出语法错误。

    $ [ ! -f ./* ]
    bash: [: too many arguments
    

    这是检查目录是否包含任何文件的更好方法:

    files=(./*) # populate an array with file or directory names
    hasfile=false
    for file in "${files[@]}"; do
       if [[ -f $file ]]; then
          hasfile=true
          break
       fi
    done
    
    if $hasfile; then
       while read -r file; do
          echo "$file"
       done < <(find . -maxdepth 1 -type f)
    fi
    

    另外,如果你有 GNU find,你可以简单地用 find -print 替换 while 循环:

    if $hasfile; then
       find . -maxdepth 1 -type f -print
    fi
    

    【讨论】:

      【解决方案3】:

      “for”的语法是

      for: for NAME [in WORDS ... ;] do COMMANDS;完成

      你错过了“完成”

      试试

      if [ ! -f ./* ]; then
        for files in $(find . -maxdepth 1 -type f); do
          echo $files
        done
      else
        echo Nothing here
      fi
      

      顺便说一句,您的意思是使用小写而不是 ECHO 的 echo 吗?

      【讨论】:

      • BTW, did you mean echo with lowercase rather than ECHO? 是的,我做到了。谢谢
      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多