0

Directory Location: /var/lib/messageFunction-7834bdfjsdfj783/data/snapshot

I have the above directory and I need to find if the directory exists using a bash script.

#!/bin/bash

if [ ! -d "/var/lib/messageFunction-*/data/snapshot" ]; then
echo NO FOLDER
else
echo FOLDER IS THERE
fi

The above script always returned "NO FOLDER" but the directory exists in the location. Can you guide how to regex to identify the subdirectory?

Thanks

Jagadeesan G
  • 495
  • 1
  • 5
  • 9
  • 2
    `'*'` is not expanded within quotes. It is literally testing for the directory named `/var/lib/messageFunction-*/data/snapshot` which won't exist. An iterative solution, as below, is the proper approach, or use `find` and loop over the output (or `grep`, etc..) Also in pathname expansion `'*'` is part of filename globbing, not a REGEX... – David C. Rankin Nov 11 '21 at 07:55
  • What if there are multiple directories matching the glob `/var/lib/messageFunction-*/data/snapshot` ? – M. Nejat Aydin Nov 11 '21 at 10:13
  • There is probably a better duplicate specifically about why not to quote `*` but I imagine you solved this already. – tripleee Nov 11 '21 at 10:43

2 Answers2

1

Not exactly what you asked for but another solution how I would solve this. First loop over all directories that match the first part and than check if the data/snapshot dirs are in there:

#!/bin/bash
for myDir in /var/lib/messageFunction-*; do
    if [ ! -d "$myDir/data/snapshot" ]; then
        echo "NO FOLDER"
    else
        echo "FOUND IN $myDir"
    fi
done
MacDefender
  • 346
  • 2
  • 6
-1

You can use "find" command (not "ls" - agree):

if [[ -n $(find /var/lib/ --max-depth=0 -type d -name "messageFunction-*" 2>/dev/null) ]]; then
    echo "OK"
else
    echo "Not found"
fi

Where:

/var/lib/ (path for search)

--max-depth=0 (don't search in sub-directories)

-type d (search only directories)

-name "messageFunction-*" (directory wildcard name)

2>/dev/null (not catch error messages)

Podrepny
  • 29
  • 3