21

It seems that you can write a negated conditional either as

if ! [[ ... ]]; then

or

if [[ ! ... ]]; then

Are there reasons to choose one or the other approach, assuming that the semantics of the operation are the same? (I.e., obviously, in the second version, if the ... is a compound statement and you're not careful to group the expression properly then you may end up negating only the first part of the expression.)

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
mhucka
  • 2,143
  • 26
  • 41
  • See: [Negate if condition in bash script](https://stackoverflow.com/q/26475358/3776858) – Cyrus Sep 04 '17 at 19:58
  • @Cyrus Thanks for the link; the answers there explain there are equivalent forms, but do not explain _why_ one would want to choose one or the other form. So, I think the present question still has independent value. – mhucka Sep 04 '17 at 21:16
  • 1
    I am also of your opinion. Therefore, I have not closed the question as a duplicate. – Cyrus Sep 04 '17 at 21:31
  • I saw this once [![:space:]] where it couldn't seem to make up it's mind. – Brain2000 Mar 19 '21 at 22:05

1 Answers1

18

No, it is completely up to your own preference. The next commands are completely equivalent:

if [[ $x -ne $y ]]; then
if ! [[ $x -eq $y ]]; then
if [[ ! $x -eq $y ]]; then

Your preferences might be based on different if conditions:

  • if [[ $x -ne $y ]]; then: Simple comparisons without any complexity like ordinary variable comparison.
  • if ! [[ $x -eq $y ]]; then: Suppose you have a complex if condition that might be a result of some function instead of $x -eq $y.
  • if [[ ! $x -eq $y ]]; then: Unnecessary, use either first or second, depending on what type of if condition you have. I would never use this one!
campovski
  • 2,979
  • 19
  • 38
  • 1
    Does this same reasoning apply to commands using single brackets? Thanks. – Josh May 10 '20 at 23:52
  • @Josh I am not sure what you mean by that. Could you provide an example please. – campovski May 11 '20 at 11:37
  • 1
    `if [ ! -d $dirname ]; then someaction; else otheraction; fi` vs. `if ! [ -d $dirname ]; then someaction; else otheraction; fi`. Thanks! – Josh May 13 '20 at 17:09
  • [This resource](https://bash.cyberciti.biz/guide/Logical_Not_!) seems to say the `!` should be inside single brackets. I'm not sure if there is consensus. – Josh May 16 '20 at 02:58
  • 1
    Inside the square brackets the exclamation mark becomes part of the boolean expression passed to "test" command. Outside the square brackets the exclamation mark is just another shell (possibly built-in) command that negates the exit code of the command to the right of it (https://stackoverflow.com/questions/367069/how-can-i-negate-the-return-value-of-a-process). – Neeme Praks Mar 27 '23 at 10:59