Confirm the existence of one or more directories

2019-08-19 12:47发布

问题:

I'd like to check of the existence of one or more directories in a Bash script using a wildcard.

I've tried this;

if [ -d app/*management ]
then
    for mscript in `ls -d app/*management`
    do
        ...
    done
fi

Which works if there is one match but throws the error "binary operator expected".

Any suggestion on a good way to do this?

回答1:

You can't use -d to check multiple directories at the same time without && (and) in your expressions. I would use this:

for dir in app/*management; do
   if [[ -d $dir ]]; then
      ...
   fi
done

You should use globs instead of parsing the output of ls. See the following link for more information: http://mywiki.wooledge.org/ParsingLs



回答2:

Why don't you do it like this:

for mscript in app/*management ; do
  if [ -d "$myscript" ] ; then
    ...
  fi
done


回答3:

After the glob expands to your list of management directories, the if statement looks like

if [ -d app/1management app/2management ]

Since -d takes only one argument, bash doesn't know what to do with the remaining directories. To bash, it looks like you forgot to include a binary operator.

You can do just do the following:

for mscript in app/*management; do
    if [ ! -d $mscript ]; then
        continue
    fi
    ...
done

EDIT: As jordanm commented, the following probably isn't necessary, but I'll leave it here for reference, as nullglob is good to know about.

One caveat. If there is a possibility that app/*management won't expand to anything, you need to set the shell option nullglob before your loop, or else "app/*management" will be treated as a literal string, not a shell glob.

if ! shopt nullglob; then
   setting_nullglob=1
   shopt -qs nullglob
fi
for mscript in app/*management; do
...
done
if [ ${setting_nullglob:-0} = 1 ]; then
    unset setting_nullglob
    shopt -qu nullglob
fi