简体   繁体   中英

zsh/bash script fails in loop when *.css doesn't have match

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM