-2

What command can be used to check if directories starting with a particular pattern exists or not, within shell script ?

For example :

In HOME path if there are many directories starting with ABCD_* and i want to check if there are any directories staring with pattern- ABCD_* exist or not using a command.

If (any directory matching this pattern exist) then echo found else echo not found fi

Atif Sheikh
  • 105
  • 4
  • 12

2 Answers2

1
find ~ -type d -name "ABCD_*"

Search the home directory of the current user (~) for directories (-type d) with the pattern "ABCD_*" (using -name)

You can then use this in an if condition by integrating it with wc -l and so:

if [[ "$(find ~ -type d -name "ABCD_*" | wc -l)"  -gt "0" ]];
then 
    echo "Found";
else
    echo "Not Found";
fi
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
0

Use a glob and count the number of matches. To ensure that only directories are matched, use a trailing /.

Counting can be done with arrays ...

shopt -s nullglob
found=(~/ABCD_*/)
if (( "${#found[@]}" > 0 )); then
  # there are directories starting with ABCD_
else
  # there are no such directories
fi

... or by a function ...

hasArgs() {
  (( $# > 0 ))
}
shopt -s nullglob
if hasArgs ~/ABCD_*/; then
  # there are directories starting with ABCD_
else
  # there are no such directories
fi
Socowi
  • 25,550
  • 3
  • 32
  • 54