为什么通配符模式与逃脱的后缀不匹配

问题描述 投票:0回答:1

我有以下bash脚本,正在其中测试一些通配符模式匹配,并期望对test的所有调用都回显match。我不明白为什么最后一种情况不匹配:

#!/bin/bash

test () {
  subject=$1
  pattern=$2
  echo "----------------"
  echo "$subject vs $pattern"
  case $subject in
    ($pattern) echo "match";;
    (*)        echo "no match";;
  esac
}

# Test question mark
test "a" "?"

# Test asterisk
test "foobar" "*"

# Test literal
test "a" "a"

# Test backslash
test "\\" "\\"

输出:

$ ./example.sh
----------------
a vs ?
match
----------------
foobar vs *
match
----------------
a vs a
match
----------------
\ vs \
no match

[我知道反斜杠用于转义,但是我不明白为什么主题和模式在相同的"\\"时不匹配-不应该以相同的方式进行转义吗?

bash wildcard glob
1个回答
0
投票

如果尝试test "\\" "\\\\"test '\' '\\',您会发现它有效。反斜杠是一个特殊字符,您需要对它进行转义/引用以实现文字匹配。

© www.soinside.com 2019 - 2024. All rights reserved.