[英]Nesting a for loop in an if else statement
if [ ! -f ./* ]; then
for files in $(find . -maxdepth 1 -type f); do
echo $files
else
echo Nothing here
fi
退貨
意外標記'else'附近的語法錯誤
這是新手。 誰能指出我做錯了什么?
你忘了done
!
if [ ! -f ./* ]; then
for files in $(find . -maxdepth 1 -type f); do
echo $files
done
else
echo Nothing here
fi
出現語法錯誤的原因是,您沒有以“ done”語句結束循環。 在這種情況下,您應該使用while循環,而不是for循環,因為如果任何文件名包含空格或換行符,for循環都會中斷。
另外,如果全局擴展到多個文件,那么您發出的測試命令也會給出語法錯誤。
$ [ ! -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循環替換為while循環:
if $hasfile; then
find . -maxdepth 1 -type f -print
fi
“ for”的語法是
為:為NAME [用WORD ...;]做命令; 完成
您錯過了“完成”
嘗試
if [ ! -f ./* ]; then
for files in $(find . -maxdepth 1 -type f); do
echo $files
done
else
echo Nothing here
fi
順便說一句,您的意思是回聲是小寫而不是ECHO嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.