E.g。
foo=(a b c)
现在,如果b
中有$foo
,我该如何轻松检查?
答案 0 :(得分:25)
您可以使用反向订阅:
pax$ foo=(a b c)
pax$ if [[ ${foo[(r)b]} == b ]] ; then ; echo yes ; else ; echo no ; fi
yes
pax$ if [[ ${foo[(r)x]} == x ]] ; then ; echo yes ; else ; echo no ; fi
no
您会在man zshparam
下的Subscript Flags
下找到数据(至少在zsh 4.3.10
下Ubuntu 10.10
下)。
或者(感谢geekosaur),您可以使用:
pax$ if [[ ${foo[(i)b]} -le ${#foo} ]] ; then ; echo yes ; else ; echo no ; fi
您只需执行以下操作即可看到您从这两个表达式中获得的内容:
pax$ echo ${foo[(i)a]} ${#foo}
1 3
pax$ echo ${foo[(i)b]} ${#foo}
2 3
pax$ echo ${foo[(i)c]} ${#foo}
3 3
pax$ echo ${foo[(i)d]} ${#foo}
4 3
答案 1 :(得分:18)
(( ${foo[(I)b]} )) \
&& echo "it's in" \
|| echo "it's somewhere else maybe"
答案 2 :(得分:4)
如果找到匹配项,反向下标将始终返回一些内容,如果未找到匹配项,则不会返回任何内容。我们可以用它来简化答案。
$ foo=(a b c)
$ [[ -n "${foo[(r)b]}" ]] && echo 'b was found.' || echo 'b was not found.'
b was found.
$ [[ -n "${foo[(r)d]}" ]] && echo 'd was found.' || echo 'd was not found.'
d was not found.