Check if directory exists and count files matching a pattern in it [duplicate]

Check if directory exists and count files matching a pattern in it [duplicate]



This question already has an answer here:



My code has a directory path incoming, e.g., $D_path from a source.


$D_path



Now I need to check if the directory path exists and the count of files with a pattern (*abcd*) in that path exists or not in an IF Condition.


*abcd*



I do not know how to use such complex expressions through bash Scripting.



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





kindly consider adding some more information in your question, along with your effort to solve the same, we will be happy to assist you
– Inder
Aug 31 at 21:21




1 Answer
1



A code-only answer. Explanations available upon request


if [[ -d "$D_path" ]]; then
files=( "$D_path"/*abcd* )
num_files=$#files[@]
else
num_files=0
fi



I forgot this: by default if there are no files matching the pattern, the files array will contain one entry with the literal string *abcd*. To have the result where the directory exists but no files match => num_files == 0, then we need to set an additional shell option:


files


*abcd*


shopt -s nullglob



This will result in a pattern that matches no files to expand to nothing. By default a pattern that matches no files will expand to the pattern as a literal string.


$ cat no_such_file
cat: no_such_file: No such file or directory
$ shopt nullglob
nullglob off

$ files=( *no_such_file* ); echo "$#files[@]"; declare -p files
1
declare -a files='([0]="*no_such_file*")'

$ shopt -s nullglob

$ files=( *no_such_file* ); echo "$#files[@]"; declare -p files
0
declare -a files='()'





Hi Glenn Thanks a lot , it worked but one thing for information I wanted to point out is ::for the directory which doesn't exist , it went to else , but for a directory with no files the counter value was showing as 1, was this expected?..
– avinash Rudra
Sep 6 at 16:18





Explanation added.
– glenn jackman
Sep 6 at 16:32

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)