Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter if exclamation point is inside or outside brackets in Bash conditionals?

Tags:

bash

shell

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.)

like image 591
mhucka Avatar asked Sep 04 '17 19:09

mhucka


People also ask

Do exclamation marks go outside brackets?

Include full stops/exclamation marks/question marks/quotation marks before the close bracket only if the complete sentence/quote is in brackets. Otherwise, punctuate after the closing bracket.

What does exclamation mark do in Bash?

Bash maintains the history of the commands executed in the current session. We can use the exclamation mark (!) to execute specific commands from the history.

Can you use brackets in Bash?

While comparing variables in Bash, we generally use single brackets ([ ]) and double brackets ([[ ]]) interchangeably. For example, we can use the expressions [ 3 -eq 3 ] or [[ 3 -eq 3 ]] while checking whether 3 is equal to 3. Both will be successful in performing the comparison.

How do I type an exclamation point in Bash?

In addition to using single quotes for exclamations, in most shells you can also use a backslash \ to escape it. That is: git commit -m "Frustrating <insert object of frustration here>\!"


1 Answers

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!
like image 95
campovski Avatar answered Oct 15 '22 22:10

campovski