Sandra Schlichting
Sandra Schlichting

Reputation: 25986

if-statement with negative condition

I am trying to make the following if-statement

if (!(zfs list -t snapshot -o name -H | grep -q secure) && (echo $days | grep -q $day) )

so when the first command doesn't return anything and the second return true, it should be executed.

If I try

if ! zfs list -t snapshot -o name -H | grep -q secure && echo $days | grep -q $day; then
  echo ok
fi

then I can't not make it fail. It always prints ok.

Question

Can anyone see what I am doing wrong?

Upvotes: 0

Views: 219

Answers (2)

choroba
choroba

Reputation: 241858

The only way how I was able to make it output ok was zfs reporting secure and $days containing $day. Any other combination (i.e. zfs not reporting secure or $daysnot containing$day`) produced no output.

As I do not have zfs, I defined a function:

function zfs () { echo secure ; } ; days=1; day=1; if ! zfs list -t snapshot -o name -H | grep -q secure && echo $days | grep -q "$day" ; then echo ok; fi
function zfs () { echo securX ; } ; days=1; day=1; if ! zfs list -t snapshot -o name -H | grep -q secure && echo $days | grep -q "$day" ; then echo ok; fi
function zfs () { echo securX ; } ; days=0; day=1; if ! zfs list -t snapshot -o name -H | grep -q secure && echo $days | grep -q "$day" ; then echo ok; fi
function zfs () { echo secure ; } ; days=0; day=1;if  ! zfs list -t snapshot -o name -H | grep -q secure && echo $days | grep -q "$day" ; then echo ok; fi

function zfs () { echo secure ; } ;  days=0; day=1; if ( ! ( zfs list -t snapshot -o name -H | grep -q secure) && (echo $days | grep -q "$day" ) ); then echo ok; fi
function zfs () { echo securX ; } ;  days=0; day=1; if ( ! ( zfs list -t snapshot -o name -H | grep -q secure) && (echo $days | grep -q "$day" ) ); then echo ok; fi
function zfs () { echo securX ; } ;  days=1; day=1; if ( ! ( zfs list -t snapshot -o name -H | grep -q secure) && (echo $days | grep -q "$day" ) ); then echo ok; fi
function zfs () { echo secure ; } ;  days=1; day=1; if ( ! ( zfs list -t snapshot -o name -H | grep -q secure) && (echo $days | grep -q "$day" ) ); then echo ok; fi

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122364

This is a workaround rather than an answer, but you could reverse the sense of the test with grep itself using -v:

if zfs list -t snapshot -o name -H | grep -qv secure && echo $days | grep -q $day; then
  echo ok
fi

although this is not quite the same in the case where zfs list -t snapshot -o name -H returns nothing at all.

Upvotes: 1

Related Questions