0

Is this the way to negate an expression, or should I put the negation inside [[ ]] ?

  if ! [[ -z "$k" ]]; then
    printf '%s\n'  \
      "[[ -z \"\$k\" ]] returns false a test for zero length"
  fi
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Dilna
  • 405
  • 1
  • 6
  • 2
    you can do it either way – Barmar May 08 '23 at 17:55
  • 4
    Also, the negation of `-z` is `-n` – Barmar May 08 '23 at 17:55
  • 1
    Did you try it? – John Bollinger May 08 '23 at 18:36
  • I tried it, but wondered what most people would prefer. Perhaps how I do it is inefficient? – Dilna May 08 '23 at 18:45
  • Yes, the expression `[[ ! -z "$k" ]]` is valid and it is equivalent to `[[ -n "$k" ]]`. – Dilna May 08 '23 at 18:48
  • It is wrong to state that this question already has answers as indicated, because indicated answer does not mention equivalence with `[[ ! -z "$k" ]]`. – Dilna May 08 '23 at 19:34
  • @Bennings: I have added an additional answer above and hope this helps you. – Cyrus May 08 '23 at 20:09
  • [Shellcheck](https://www.shellcheck.net/) reports a style issue with both options. [Shellcheck](https://www.shellcheck.net/) can identify many common problems with shell code. The report includes links to more information about the problems and how to fix them. It's a good idea to run [Shellcheck](https://www.shellcheck.net/) on all new and modified shell code. – pjh May 08 '23 at 20:40
  • 1
    In this case, `if [[ -n $k ]]; then` is simpler and clearer than both options. Some might prefer the even shorter, but equivalent, `if [[ $k ]]; then` – pjh May 08 '23 at 20:42

0 Answers0