How to check the result of a filename extension in bash?

I want to check if the directory has files or not in bash. My code is here.

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

The problem is that "~ / .bash / completion.d" does not have a file. So, $ d / * is considered as a simple line "~ / .bash / completion.d / *", and not an empty line, which is the result of a file name extension. As a result of this code, bash tries to run

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

and, of course, generates an error message.

Can someone help me?

+3
source share
5 answers

If you set the nullglob bash parameter, through

shopt -s nullglob

then globbing will drop patterns that do not match any file.

+6
source
# 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

, , , ( , ), , script. , , .
, ( , ):

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

/, , !

+4

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

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

Source: https://habr.com/ru/post/1715699/


All Articles