如何通过几个测试来构建一个复合条件(至少1个是正则是Regex)
我搜索了这个,但没有找到这种特殊情况的答案。我熟悉外壳中的文件测试,并使用[[]]语法执行正则匹配。
有没有办法将这两个操作结合在不需要多个嵌套IF的复合条件下?
到目前为止,我尝试了以下(...以及其他更加疯狂的变化):
if [ -e ~/.profile -a $0 =~ bash ]; then echo yes ; fi
if [ -e ~/.profile -a ( $0 =~ bash ) ]; then echo yes ; fi
if [ -e ~/.profile -a [ $0 =~ bash ] ]; then echo yes ; fi
if [[ -e ~/.profile -a $0 =~ bash ]]; then echo yes ; fi
if [[ ( -e ~/.profile ) -a ( $0 =~ bash ) ]]; then echo yes ; fi
if [ -e ~/.profile -a $0 =~ bash ]; then echo yes; fi
if [ -e ~/.profile -a $( [ $0 =~ bash ] ) ]; then echo yes; fi
if [ -e ~/.profile -a [[ $0 =~ bash ]] ]; then echo yes; fi
if [ -e ~/.profile -a $([[ $0 =~ bash ]]) ]; then echo yes; fi
I searched for this but haven't found an answer to this particular situation. I'm familiar with file tests in shells and with using the [[ ]] syntax to perform regex matching.
Is there a way to combine these two operations in a compound conditional that doesn't require multiple nested ifs?
So far I've tried the following (...and other much crazier variations):
if [ -e ~/.profile -a $0 =~ bash ]; then echo yes ; fi
if [ -e ~/.profile -a ( $0 =~ bash ) ]; then echo yes ; fi
if [ -e ~/.profile -a [ $0 =~ bash ] ]; then echo yes ; fi
if [[ -e ~/.profile -a $0 =~ bash ]]; then echo yes ; fi
if [[ ( -e ~/.profile ) -a ( $0 =~ bash ) ]]; then echo yes ; fi
if [ -e ~/.profile -a $0 =~ bash ]; then echo yes; fi
if [ -e ~/.profile -a $( [ $0 =~ bash ] ) ]; then echo yes; fi
if [ -e ~/.profile -a [[ $0 =~ bash ]] ]; then echo yes; fi
if [ -e ~/.profile -a $([[ $0 =~ bash ]]) ]; then echo yes; fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用单括号时,
-a
被视为AND
,例如:对于双括号,您要使用
&&
,例如:无论您使用的是单括号还是双括号,您都可以使用
&&
来分隔测试,例如:注意:相同的规则适用于
-o 与
||
(又名<代码>或)-a
is treated as anAND
when using single brackets, eg:For double brackets you want to use
&&
, eg:Alternatively you can
&&
to separate tests regardless of whether you're using single or double brackets, eg:NOTE: same rules apply for
-o
vs||
(akaOR
)显然,当您想表示逻辑时,并且在这两个语句之间时,您必须使用&amp; amp;而不是
-a
(shell将其解释为“是否存在此文件”的文件测试中的“是否存在”)。另外,要使正则表达式工作,该语句必须在[[]]
中。当时我还不知道的是,即使-a
在双括号中更改其含义,-w
-r
和其他文件测试不会更改其功能(例如,单括号或双括号相同)。Apparently, when you want to represent a LOGICAL AND between these two statements, you must use && instead of
-a
(which the shell interprets as "does this file exist" file test in double brackets). Also, for the regex to work, the statement must be within[[ ]]
. What was unknown to me at the time is that even though-a
changes its meaning in double brackets, the-e
-w
-r
and other file tests don't change their functionality (e.g. it's the same for single or double brackets).