在 Bash 中测试 glob 是否有任何匹配项 [英] Test whether a glob has any matches in Bash

查看:21
本文介绍了在 Bash 中测试 glob 是否有任何匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想检查单个文件是否存在,我可以使用 test -e filename[ -e filename ] 来测试它.

If I want to check for the existence of a single file, I can test for it using test -e filename or [ -e filename ].

假设我有一个 glob,我想知道是否存在名称与 glob 匹配的文件.glob 可以匹配 0 个文件(在这种情况下我不需要做任何事情),或者它可以匹配 1 个或多个文件(在这种情况下我需要做一些事情).如何测试 glob 是否有任何匹配项?(我不在乎有多少匹配项,如果我能用一个 if 语句和没有循环来做到这一点最好(只是因为我觉得它最易读).

Supposing I have a glob and I want to know whether any files exist whose names match the glob. The glob can match 0 files (in which case I need to do nothing), or it can match 1 or more files (in which case I need to do something). How can I test whether a glob has any matches? (I don't care how many matches there are, and it would be best if I could do this with one if statement and no loops (simply because I find that most readable).

(test -e glob* 如果 glob 匹配多个文件,则失败.)

(test -e glob* fails if the glob matches more than one file.)

推荐答案

Bash-特定解决方案:

Bash-specific solution:

compgen -G "<glob-pattern>"

对模式进行转义,否则它会被预先扩展为匹配项.

Escape the pattern or it'll get pre-expanded into matches.

退出状态为:

  • 1 表示不匹配,
  • 0 表示一个或多个匹配项"

stdout 是一个 与 glob 匹配的文件的列表.我认为这是在简洁性和最小化潜在副作用方面的最佳选择.

stdout is a list of files matching the glob. I think this is the best option in terms of conciseness and minimizing potential side effects.

示例:

if compgen -G "/tmp/someFiles*" > /dev/null; then
    echo "Some files exist."
fi

这篇关于在 Bash 中测试 glob 是否有任何匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆