Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the opposite of the if construct in Bash?

Tags:

bash

if date -d "2012010123" runs if the date command returns a zero exit code. How do I get the opposite to occur? In other words, how can I get the if statement to run if the exit code is 1?

like image 928
imagineerThat Avatar asked Jan 14 '14 06:01

imagineerThat


People also ask

How do you negate if statements in bash?

How to negate an if condition in a Bash if statement? (if not command or if not equal) To negate any condition, use the ! operator, for example: if ! <test-command>; then <command-on-failure>; fi .

How do you negate an IF condition?

Negation of "If A, then B". To negate a statement of the form "If A, then B" we should replace it with the statement "A and Not B". This might seem confusing at first, so let's take a look at a simple example to help understand why this is the right thing to do.

How do you negate a condition in shell script?

NegationWhen we use the not operator outside the [[, then it will execute the expression(s) inside [[ and negate the result. If the value of num equals 0, the expression returns true. But it's negated since we have used the not operator outside the double square brackets.

What does != Mean in bash?

The origin of != is the C family of programming languages, in which the exclamation point generally means "not". In bash, a ! at the start of a command will invert the exit status of the command, turning nonzero values to zero and zeroes to one.


1 Answers

Negate it:

if ! date -d "2012010123"; then
  # do something here (date returned with non-zero exit code)
fi

if takes a command pipeline (or a list thereof), and of pipelines man bash says this:

The return status of a pipeline is the exit status of the last command[...] If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above.

like image 199
devnull Avatar answered Sep 22 '22 21:09

devnull