0

I am having some trouble understand test command in shell scripting.

From this piece of code here:

if [ ! "$n_trig" -a "$i_trig" ]
then 
    usage
    echo "Required options -n and -i are not present"
    exit 1
fi

I would expect the command list in the if statement to be executed since n_trip and i_trig are both set to false.. However it does not execute. If I remove ! it does. I don't understand why.

Here is the output of sh -x ./script:

+ n_trig=false
+ i_trig=false
+ p_trig=false
+ getopts n:i:p: opt
+ '[' '!' false -a false ']'
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
mrQWERTY
  • 4,039
  • 13
  • 43
  • 91

2 Answers2

2

The ! operator is just being applied only to the sub-expression "$n_trig", not to the entire expression. You can either use it outside the test, as part of the if command:

if ! [ "$n_trig" -a "$i_trig" ]

or you can use parentheses inside the test command:

if [ ! \( "$n_trig" -a "$i_trig" \) ]

Also, test "$var" just tests whether the variable is not empty, it doesn't treat the value false as false. If a variable can contain true or false, you should do:

if ! [ "$n_trig" != true -a "$i_trig" != true ]
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Have a look at this: How to declare and use boolean variables in shell script?

Booleans in shell scripts are not super reliable as there is lots of variation between different shells.

That said your test is not correct since the ! only applies to the first value

#!/bin/bash
if [ true != "$n_trig" ]  && [  true !=  "$i_trig" ]
then
    usage
    echo "Required options -n and -i are not present"
    exit 1
fi
Community
  • 1
  • 1
stringy05
  • 6,511
  • 32
  • 38
  • It's not so much that boolean variables are not reliable; it's that they don't exist. Shell scripts have exactly one type, strings, which is why you need, for example, separate operators for string ("=") and integer ("-eq") comparisons. – chepner May 02 '15 at 02:29