Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash "not": inverting the exit status of a command

I know I can do this...

if diff -q $f1 $f2
then
    echo "they're the same"
else
    echo "they're different"
fi

But what if I want to negate the condition that I'm checking? i.e. something like this (which obviously doesn't work)

if not diff -q $f1 $f2
then
    echo "they're different"
else
    echo "they're the same"
fi

I could do something like this...

diff -q $f1 $f2
if [[ $? > 0 ]]
then
    echo "they're different"
else
    echo "they're the same"
fi

Where I check whether the exit status of the previous command is greater than 0. But this feels a bit awkward. Is there a more idiomatic way to do this?

like image 423
Coquelicot Avatar asked Feb 25 '13 17:02

Coquelicot


People also ask

How do I ignore a bash output?

If you are looking to suppress or hide all the output of a bash shell script from Linux command line as well as from the crontab then you can simply redirect all the output to a file known as /dev/null . This file is known as Black Hole which will engulf everything you give without complaining.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

How do you exit a shell script gracefully?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do you check exit status in bash?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?


2 Answers

if ! diff -q "$f1" "$f2"; then ...
like image 97
William Pursell Avatar answered Sep 21 '22 19:09

William Pursell


If you want to negate, you are looking for ! :

if ! diff -q $f1 $f2; then
    echo "they're different"
else
    echo "they're the same"
fi

or (simplty reverse the if/else actions) :

if diff -q $f1 $f2; then
    echo "they're the same"
else
    echo "they're different"
fi

Or also, try doing this using cmp :

if cmp &>/dev/null $f1 $f2; then
    echo "$f1 $f2 are the same"
else
    echo >&2 "$f1 $f2 are NOT the same"
fi
like image 32
Gilles Quenot Avatar answered Sep 19 '22 19:09

Gilles Quenot