Pergunta

Suppose I am writing the following in a bash script:

if [ -z $a ] || [ -z $b ] ; then
    usage
fi

It works but I would like to write it with short-circuiting as follows:

[ -z $a ] || [ -z $b ] || usage

Unfortunately it does not work. What am I missing ?

Foi útil?

Solução

You want to execute usage in case either 1st or 2nd condition are accomplished. For that, you can do:

[ -z $a ] || [ -z $b ] && usage

Test:

$ [ -z "$a" ] || [ -z "$b" ] && echo "yes"
yes
$ b="a"
$ [ -z "$a" ] || [ -z "$b" ] && echo "yes"
yes
$ a="a"
$ [ -z "$a" ] || [ -z "$b" ] && echo "yes"
$ 

Outras dicas

You could make use of the following form:

[[ expression ]]

and say:

[[ -z "$a" || -z "$b" ]] && usage

This would execute usage if either a or b is empty.


Always quote your variables. Saying

[ -z $a ]

if the variable a is set to foo bar would return an error:

bash: [: foo: binary operator expected
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top