我想告诉您一个字符串$string是否可以通过glob模式进行匹配$pattern。 $string可能是也可能不是现有文件的名称。我怎样才能做到这一点?
假设我的输入字符串采用以下格式:
string="/foo/bar"
pattern1="/foo/*"
pattern2="/foo/{bar,baz}"
我想找到一个bash成语,决定是否$string将被匹配$pattern1,$pattern2或任何其它任意的glob模式。到目前为止,这是我尝试过的:
[[ "$string" = $pattern ]]除了
$pattern被解释为字符串模式而不是全局模式之外,这几乎可以工作。[ "$string" = $pattern ]这种方法的问题
$pattern是先进行扩展,然后在之间进行字符串比较,然后$string对进行扩展$pattern。[[ "$(find $pattern -print0 -maxdepth 0 2>/dev/null)" =~ "$string" ]]该
$string文件有效,但前提是包含一个存在的文件。[[ $string =~ $pattern ]]这不起作用,因为
=~运算符导致$pattern将其解释为扩展的正则表达式,而不是全局或通配符模式。
ls /foo/* 现在您可以参加
foo/{bar,baz}实际上是大括号扩展(不是参数扩展),而foo/*实际上是路径名扩展。 $string是参数扩展。这些都是在不同的时间和通过不同的机制完成的。
case语句按照Bash手册执行Pathname Expansion(“ globbing”)。
{bar,baz}不是模式。它是参数扩展。细微但关键的区别{bar,baz}很早就扩展为多个论点,bar并且baz。