2009-08-21 38 views
3

我想檢查一個目錄是否有文件或不在bash中。 我的代碼在這裏。如何在bash中測試文件名擴展結果?

for d in {,/usr/local}/etc/bash_completion.d ~/.bash/completion.d 
    do    
     [ -d "$d" ] && [ -n "${d}/*" ] &&       

     for f in $d/*; do                           
      [ -f "$f" ] && echo "$f" && . "$f"       

     done                               
    done 

問題是「〜/ .bash/completion.d」沒有文件。 因此,$ d/*被認爲是簡單的字符串「〜/ .bash/completion.d/*」,而不是作爲文件名擴展結果的空字符串。 作爲該代碼的結果時,bash試圖運行

. "~/.bash/completion.d/*" 

,當然,它產生錯誤消息。

任何人都可以幫助我嗎?

+0

簡而言之,我想知道如何爲無效的文件名字符串強制擴展文件名。 – user159087 2009-08-21 09:44:22

回答

6

如果您設置的bash了nullglob選項,通過

shopt -s nullglob 

則通配符將下降不匹配任何文件的模式。

+0

kjshim的代碼似乎對我很有用,因爲它沒有設置'nullglob'('shopt nullglob'返回「off」)。任何想法,爲什麼這可能是? – 2009-08-21 13:18:37

+0

也許你一直在嘗試的目錄不是空的? – 2009-08-21 13:26:15

+0

'ls -la test'顯示'.'和'..' – 2009-08-21 17:01:45

0

您可以通過以下方式直接使用find

for f in $(find {,/usr/local}/etc/bash_completion.d ~/.bash/completion.d -maxdepth 1 -type f); 
do echo $f; . $f; 
done 

find將打印一個警告,如果某些目錄中是找不到的,你可以把一個2> /dev/null或將find呼叫測試後如果目錄存在(如你的代碼)。

0
find() { 
for files in "$1"/*;do 
    if [ -d "$files" ];then 
     numfile=$(ls $files|wc -l) 
     if [ "$numfile" -eq 0 ];then 
      echo "dir: $files has no files" 
      continue 
     fi 
     recurse "$files" 
    elif [ -f "$files" ];then 
     echo "file: $files"; 
     : 
    fi 
done 
} 
find /path 
+0

漂亮的代碼。它有什麼作用? – 2011-09-29 19:10:03

0

另一種方法

# prelim stuff to set up d 
files=`/bin/ls $d` 
if [ ${#files} -eq 0 ] 
then 
    echo "No files were found" 
else 
    # do processing 
fi 
4
 
# NOTE: using only bash builtins 
# Assuming $d contains directory path 

shopt -s nullglob 

# Assign matching files to array 
files=("$d"/*) 

if [ ${#files[@]} -eq 0 ]; then 
    echo 'No files found.' 
else 
    # Whatever 
fi 

分配到一個陣列具有其他的好處,包括含白色空間,和簡單的迭代的文件名/路徑期望的(正確!)處理,而無需使用一個子如以下代碼所示:

 
find "$d" -type f | 
while read; do 
    # Process $REPLY 
done 

取而代之,您可以使用:

 
for file in "${files[@]}"; do 
    # Process $file 
done 

與環路內進行該循環由主殼運行,這意味着副作用(如變量賦值,說)下的權益是用於腳本的其餘部分是可見的。當然,這也是方式更快,如果性能是一個問題。
最後,陣列也可以在命令行參數插入(不含空格拆分參數):

 
$ md5sum fileA "${files[@]}" fileZ 

你應該總是嘗試正確處理文件/包含空格的路徑,因爲有一天,他們會發生!

+0

對於文件glob擴展的很好例子,bash手冊對這部分非常混淆! – 2011-08-23 00:15:31

相關問題