否定Bash中的多个条件 [英] Negating multiple conditions in Bash

查看:131
本文介绍了否定Bash中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这是一个简单的问题,但是由于bash中严格的语法要求,我很难找到答案.我有以下脚本:

I realize this is a simple question, but I am finding a hard time getting an answer due to the finnicky syntax requirements in bash. I have the following script:

if ! [ [ -z "$1" ] || [ -z "$2" ] ]; then
  echo "both arguments are set!"
fi

运行时不带参数的输出如下:

I get the following output when I run it without arguments:

./test: line 3: [: -z: binary operator expected 
both arguments are set!

我不希望有任何输出-均未设置任何参数.我在做什么错了?

I am not expecting any output - neither argument is set. What am I doing wrong?

推荐答案

内置于[test shell支持参数-a-o,它们分别是逻辑AND和OR.

The test shell builtin [ supports the arguments -a and -o which are logical AND and OR respectively.

#!/bin/sh 

if [ -n "$1" -a -n "$2" ]
then echo "both arguments are set!"
fi

在这里,我使用-n来检查字符串的长度是否为非零而不是-z,这表明字符串 的长度为零,因此必须用!取反.

Here I use -n to check that the strings are non-zero length instead of -z which shows that they are zero length and therefore had to be negated with a !.

"-n string如果字符串的长度非零,则为true."

" -n string True if the length of string is nonzero."

-z字符串,如果字符串的长度为零,则为true."

"-z string True if the length of string is zero."

如果使用的是bash,它还支持更强大的测试类型[[]],可以使用布尔运算符||&&:

If you are using bash it also supports a more powerful type of test [[]] which can use the boolean operators || and &&:

#!/bin/bash 

if [[ -n "$1" && -n "$2" ]]
then echo "both arguments are set!"
fi

在评论中,解决了这些示例均未显示如何在shell中取反多个测试的问题,下面是一个示例:

In comments it was addressed that none of these samples show how to negate multiple tests in shell, here is an example which does:

#!/bin/sh 

if [ ! -z "$1" -a ! -z "$2" ]
then echo "both arguments are set!"
fi

这篇关于否定Bash中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆