bash 在 if else 语句中嵌套 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9023833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:26:18  来源:igfitidea点击:

Nesting a for loop in an if else statement

bashshellif-statementfor-loop

提问by Mechaflash

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

Returns

退货

syntax error near unexpected token `else'

意外标记“else”附近的语法错误

New to this. Can anyone point me to what I did wrong?

新来的。谁能指出我做错了什么?

回答by Mischa Arefiev

You forgot done!

你忘了done

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

回答by jordanm

The reason you get a syntax error is because you are not ending the loop with the "done" statement. You should be using a while loop, instead of a for loop in this case, as the for loop will break if any of the filenames contain spaces or newlines.

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

Also, the test command you have issued will also give a syntax error if the glob expands to multiple files.

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

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

Here is a better way to check if the directory contains any files:

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

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

Also, you could simply replace the while loop with find -print if you have GNU find:

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

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

回答by Roger Lindsj?

The syntax for "for" is

“for”的语法是

for: for NAME [in WORDS ... ;] do COMMANDS; done

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

You are missing the "done"

你错过了“完成”

Try

尝试

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

BTW, did you mean echo with lowercase rather than ECHO?

顺便说一句,你的意思是用小写而不是 ECHO 回声?