Search code examples
bash

Bash: ! inside or outside of square brackets


Is there any meaningful/behavioural difference between putting a ! inside or outside of square bracket tests?

e.g. Is there a difference between:

# if file exists but is empty, exit
[[ ! -s "${file}" ]] && exit 1

and

# if file exists but is empty, exit
! [[ -s "${file}" ]] && exit 1

I'm asking generally, not specific to the -s test. For example, does any of this change when working with numbers, or with multiple tests?


Solution

  • It negates everything inside the brackets if you place it outside the brackets. It's an if not (negates the adjacent term) only if you place it inside the brackets. Consider multiple terms with && (and ||) like

    ! [[ -s "/usr/bin/env" || "1" == "0" ]] && echo true
    

    is logically different from

    [[ -s "/usr/bin/env" || ! "1" == "0" ]] && echo true