假设我有以下Bash代码段:
if [[ "$foo" == *"$bar"* ]] ; then
echo 'condition is true'
fi
In English, you might describe the above code with: if bar
is a substring of foo
then...
但是,当我们切换条件的条件时,为什么没有得到相同的结果呢?
if [[ *"$bar"* == "$foo" ]] ; then
echo 'condition is true'
fi
也许我对通配符的计算时间有误解?
==比较运算符在双括号内的行为有所不同:
This works because bash's builtin
[[
operator treats the right-hand-side of an == test as a pattern:It's an explicit design decision. Here's
man bash
:Pathname expansion is not performed in
[[ .. ]]
, so regular rules around that don't apply.Treating both as a pattern would be pretty strange. Should
[[ [a]* == [a]* ]]
be false because neither string matches the pattern on the other side, or should it be true because the patterns match the same set of strings?