bash if 语句中带有变量的通配符
bash wildcard with variables inside an if statement
我想根据this solution.
在字符串中查找子串
但由于某些原因它不适用于变量:
str="abcd";
substr="abc";
if [[ "${substr}"* == ${str} ]]
then
echo "CONTAINS!";
fi
在参考手册section Conditional Constructs中,您将阅读[[ ... ]]
的文档:
When the ==
and !=
operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching, as if the extglob
shell option were enabled.
(强调是我的)
因此您需要将 glob 模式 放在 ==
运算符的右侧 :
if [[ $str == "$substr"* ]]; then
注意左边不用引号,右边的$substr
部分需要引号,以防包含glob 字符,如 *
、?
、[...]
、+(...)
等
我想根据this solution.
在字符串中查找子串但由于某些原因它不适用于变量:
str="abcd";
substr="abc";
if [[ "${substr}"* == ${str} ]]
then
echo "CONTAINS!";
fi
在参考手册section Conditional Constructs中,您将阅读[[ ... ]]
的文档:
When the
==
and!=
operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching, as if theextglob
shell option were enabled.
(强调是我的)
因此您需要将 glob 模式 放在 ==
运算符的右侧 :
if [[ $str == "$substr"* ]]; then
注意左边不用引号,右边的$substr
部分需要引号,以防包含glob 字符,如 *
、?
、[...]
、+(...)
等