0

I have a directory named .poco that has subdirectories at different levels. Some have *.css files in them. Some don't. The following script fails on line 4 (the second for loop) if the current directory has no .css files in it. How do I keep the script running if the current directory doesn't happen to have a match to *.css?

#!/bin/zsh
for dir in ~/pococms/poco/.poco/*; do
    if [ -d "$dir" ]; then
    for file in $dir/*.css # Fails if directory has no .CSS files
      do
        if [ -f $file ]; then
          v "${file}"
        fi
      done
    fi
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
tomcam
  • 4,625
  • 3
  • 19
  • 22
  • 3
    Does this answer your question? [Why zsh tries to expand \* and bash does not?](https://stackoverflow.com/questions/20037364/why-zsh-tries-to-expand-and-bash-does-not) – Barmar Jan 28 '23 at 21:08
  • 1
    `for file in ~/pococms/poco/.poco/*/*.css(.):`. No need for nested loops or the `if` statement. (The proposed duplicate takes care of non-matching patterns.) – chepner Jan 28 '23 at 21:23

1 Answers1

0

That happens because of "shell globbing". Your shell tries to replace patterns like *.css with the list of files. When no files match the pattern, you get the "error" that you get.

You might want to use find:

find ~/pocoms/poco/.poco -mindepth 2 -maxdepth 2 -type f -name '*.css'

and then xargs to your program (in that case - echo) like:

find ~/pocoms/poco/.poco\
  -mindepth 2\
  -maxdepth 2\
  -type f\
  -name '*.css'\
  -print0\
| xargs -0 -n1 -I{} echo "{}"

-n1 to pass the files one by one, remove it if you want your program to accept the full list of files as args.

storoj
  • 1,851
  • 2
  • 18
  • 25
  • That did the trick. Still trying to parse these options so I understand them thoroughly but until, I've got perfectly working c0de. Thanks you! – tomcam Feb 04 '23 at 23:37