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.
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
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