Confirm the existence of one or more directories

2019-08-19 12:38发布

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?

3条回答
Anthone
2楼-- · 2019-08-19 13:21

Why don't you do it like this:

for mscript in app/*management ; do
  if [ -d "$myscript" ] ; then
    ...
  fi
done
查看更多
叼着烟拽天下
3楼-- · 2019-08-19 13:24

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

查看更多
在下西门庆
4楼-- · 2019-08-19 13:32

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
查看更多
登录 后发表回答