2016-10-24 164 views
1

在我的bash腳本中,我有一個目錄中的文件循環和一個簡單的if語句來篩選特定文件。但是,它不像我預期的那樣,但我不明白爲什麼。Bash:if語句循環

(我知道我可以爲已經文件擴展名的for循環表達式(... in "*.txt")過濾器,但條件是在我的實際情況要複雜得多。)

這是我的代碼:

#!/bin/bash 
for f in "*" 
do 
    echo $f 
    if [[ $f == *"txt" ]] 
    then 
     echo "yes" 
    else 
     echo "no" 
    fi 
done 

輸出我得到:

1001.txt 1002.txt 1003.txt files.csv 
no 

我會期待什麼:

1001.txt 
yes 
1002.txt 
yes 
1003.txt 
yes 
files.csv 
no 

回答

1

腳本中引用錯誤的問題。您在glob的頂部有額外的報價,並且在echo中缺少報價。

有這樣說:

for f in * 
do 
    echo "$f" 
    if [[ $f == *"txt" ]] 
    then 
     echo "yes" 
    else 
     echo "no" 
    fi 
done 
  • for f in "*"將循環只f如字面一次*
  • 非上市echo $f將擴大*輸出所有匹配的文件/當前目錄的目錄。
+1

我知道那是這麼簡單......謝謝! – Tobias