-3

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

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.

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

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
A_R
  • 19
  • 4
  • 1
    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 '18 at 21:21

1 Answers1

2

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:

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='()'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • 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?.. – A_R Sep 06 '18 at 16:18