Bash 不使用“否定正则表达式测试”;如果;

Bash 不使用“否定正则表达式测试”;如果;,bash,Bash,好吧,我想“bash”是“把头撞进去”的缩写 得到这个: ! [[ $var =~ ^[0-9]+$ ]] && echo "Supply integer values from the menu only. Nothing added." && return; 它不起作用。我必须这样做: if ! [[ $var =~ ^[0-9]+$ ]]; then echo "Supply integer values from the menu only. N

好吧,我想“bash”是“把头撞进去”的缩写

得到这个:

! [[ $var =~ ^[0-9]+$ ]] && echo "Supply integer values from the menu only. Nothing added." && return;
它不起作用。我必须这样做:

if ! [[ $var =~ ^[0-9]+$ ]]; then
    echo "Supply integer values from the menu only. Nothing added." && return
fi
有没有办法让第一种方法发挥作用


更新:原始代码已编辑。上面编辑的代码工作正常。这是我在反复思考如何否定正则表达式时犯的一个愚蠢的错误。结束此操作。

问题在于操作/操作分组的顺序。可以使用大括号在bash中对操作进行分组;像这样:

! [[ $var =~ ^[0-9]+$ ]] || { echo "Supply integer values from the menu only. Nothing added." && return; }
请注意,
在花括号内的代码末尾是非常必要的。

不清楚什么是“不起作用”的意思,但您的两个语句并不相等

1195$ ! false || echo hello
1196$ ! true || echo hello
hello

1197$ if ! false; then echo hello ; fi
hello
1198$ if ! true; then echo hello ; fi
正确和错误在两种不同用法之间的作用是相反的。

第二种用法是:

if ! [[ $var =~ ^[0-9]+$ ]]; then
  echo "Supply integer values from the menu only. Nothing added." && return
fi
所以回声。。。当正则表达式不匹配时执行。 但在第一个示例中,使用OR(| |在bash中):

因此,当<代码>执行时,将执行回显![[…]
表达式失败,这与使用if编写的相反。同样是:

! [[ $var =~ ^[0-9]+$ ]] && echo "Supply integer values from the menu only. Nothing added." && return;

事实上,我想我在那里有一个
|
,我的意思是
&&
。这将真正解释行为上的差异是的。现在,我假设您的两个代码示例都执行相同的操作。无论如何,如果您想使用
|
操作符,我的答案仍然有效;因为bash操作顺序并不是那么简单,我搞砸了。我尝试了不同的方法让正则表达式取反,其中一种方法是将
&
更改为
|
。我不知道该把感叹号放在哪里。
! [[ $var =~ ^[0-9]+$ ]] && echo "Supply integer values from the menu only. Nothing added." && return;