簡體   English   中英

如何在bash中測試文件名擴展結果?

[英]How to test filename expansion result in 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/*" 

當然,它會生成錯誤消息。

有誰能夠幫助我?

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

shopt -s nullglob

然后globbing將刪除與任何文件都不匹配的模式。

# 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

分配給數組還有其他好處,包括對包含空白的文件名/路徑的理想(正確!)處理,以及不使用子shell的簡單迭代,如下面的代碼所示:

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

相反,你可以使用:

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

這個循環由主shell運行,這意味着在循環中產生的副作用(例如變量賦值)對於腳本的其余部分是可見的。 當然,它也是更快的方式 ,如果性能是一個問題。
最后,還可以在命令行參數中插入數組(不拆分包含空格的參數):

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

你應該總是試圖正確處理包含空白區域的文件/路徑,因為有一天它們會發生!

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

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

但是如果find某個目錄, find會打印一個警告,你可以放一個2> /dev/null或者在測試后放置find調用,如果目錄存在(比如代碼中)。

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

另一種方法

# prelim stuff to set up d
files=`/bin/ls $d`
if [ ${#files} -eq 0 ]
then
    echo "No files were found"
else
    # do processing
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM