-2

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.

1
  • 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 Commented Aug 31, 2018 at 21:21

1 Answer 1

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='()' 
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.