Cancel if condition in bash script

I'm new to bash, and I'm stuck trying to nullify 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 am connected to the Internet. I want this to happen the other way around, but placement ! anywhere doesn't work.

+65
linux bash if-statement
Oct 20 '14 at
source share
5 answers

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 next expression, respectively.

+83
Oct 20 '14 at
source share
β€” -

better

 if ! wget -q --spider --tries=10 --timeout=20 google.com then echo 'Sorry you are Offline' exit 1 fi 
+42
Oct 20 '14 at 22:19
source share

If you feel lazy, here's a brief method for handling conditions using || (or) and && (and) after the operation:

 wget -q --tries=10 --timeout=20 --spider http://google.com || \ { echo "Sorry you are Offline" && exit 1; } 
+5
Oct 20 '14 at 21:59
source share

You can use the unequal comparison -ne instead of -eq :

 wget -q --tries=10 --timeout=20 --spider http://google.com if [[ $? -ne 0 ]]; then echo "Sorry you are Offline" exit 1 
+4
Oct 20 '14 at 21:40
source share

Since you are comparing numbers, you can use an arithmetic expression that allows you to simplify parameter processing and comparison:

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

Note that instead of -ne you can just use != . In an arithmetic context, we don’t even need to add $ to the parameters, i.e.

 var_a=1 var_b=2 (( var_a < var_b )) && echo "a is smaller" 

works great. However, this does not apply to the special parameter $? .

The construct (( ... )) is available in Bash, but the POSIX shell specification is not required (referred to as a possible extension, though).

All that is said, is it better to avoid $? in general, in my opinion, how to answer in Cole and Stephen to answer .

+3
Jun 04 '16 at 21:29
source share



All Articles