Negate if condition in bash script

Sudh33ra picture Sudh33ra · Oct 20, 2014 · Viewed 196.5k times · Source

I'm new to bash and I'm stuck at trying to negate the following command:

wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -eq 0 ]]; then
        echo "Sorry you are Offline"
        exit 1

This if condition returns true if I'm connected to the internet. I want it to happen the other way around but putting ! anywhere doesn't seem to work.

Answer

Cyrus picture Cyrus · Oct 20, 2014

You can choose:

if [[ $? -ne 0 ]]; then       # -ne: not equal

if ! [[ $? -eq 0 ]]; then     # -eq: equal

if [[ ! $? -eq 0 ]]; then

! inverts the return of the following expression, respectively.