alabamatoy
alabamatoy

Reputation: 101

Bash "if" condition

Ubuntu 16.04...I have a script to check external IP address:

GETIPADDR=`wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'`
...

if [ $GETIPADDR = "" ]; then

The GETIPADDR line works under normal conditions, and $GETIPADDR will have the string value of the external IPv4 address. When external connectivity is lacking or some other problem occurs with the wget, an echo of $GETIPADDR shows it has no content, but the if does not return a true condition (the "then" does not execute).

Can someone educate me as to why? What am I doing wrong here?

Upvotes: 0

Views: 66

Answers (1)

chepner
chepner

Reputation: 530920

You have to quote the expansion of $GETIPADDR; otherwise, the empty string is removed from the command line before [ runs, and you get a syntax error.

if [ "$GETIPADDR" = "" ]; then

Your code, if the variable is empty, is equivalent to

if [ = "" ]; then

not

if [ "" = "" ]; then

The preferred way to check for an empty string is to use the -z operator:

if [ -z "$GETIPADDR" ]; then

Upvotes: 2

Related Questions