测试一个水珠是否在bash任何比赛 [英] Test whether a glob has any matches in bash

查看:86
本文介绍了测试一个水珠是否在bash任何比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要检查一个文件是否存在等,我可以使用测试它测试-e文件名 [-e文件名]

假如我有水珠,我想知道的任何文件中是否存在其名称匹配的水珠。水珠可以匹配0文件(在这种情况下,我需要做什么),也可以搭配1个或多个文件(在这种情况下,我需要做的事情)。如何测试一个水珠是否有比赛吗? (我不在乎有多少场比赛也有,这将是最好的,如果我能做到这一点与一个如果语句,并没有循环(只是因为我发现,最可读)。

测试-e水珠* 如果水珠匹配多个文件失败。)


解决方案

  compgen -G<水珠图案>中

逃脱模式或将得到pre-扩展到匹配。
退出状态是1无匹配,0'一个或多个匹配。
stdout是文件匹配的glob的列表。
我认为这是简洁和减少潜在的副作用而言是最好的选择。

更新:用法示例要求

 如果compgen -G的/ tmp / someFiles *>的/ dev / null的;然后
    回声某些文件存在。
科幻

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

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* fails if the glob matches more than one file.)

解决方案

compgen -G "<glob-pattern>"

Escape the pattern or it'll get pre-expanded into matches. Exit status is 1 for no-match, 0 for 'one or more matches'. stdout is a list of file matching the glob. I think this is the best option in terms of conciseness and minimizing potential side effects.

UPDATE: Example usage requested.

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

这篇关于测试一个水珠是否在bash任何比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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