imagineerThat
imagineerThat

Reputation: 5553

How do I get the opposite of the if construct in 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?

Upvotes: 8

Views: 9667

Answers (1)

devnull
devnull

Reputation: 123608

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.

Upvotes: 13

Related Questions