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?
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With