Skip to content
Advertisement

how to write Bash script for getting Public ip address in a way that when one command failed then it have to execute another command

i want to write a bash script in a way that if one command gets failed then it will have to execute another command. For example:- “curl www.ifconfig.me” if this command gets failed then another command “curl http://icanhazip.com” to get execute and should show the output.

Advertisement

Answer

If you want the HTTP code, try this:

$ RETURN_STRING=$(curl --silent --url "www.ifconfig.me" --write-out "nHTTP_CODE:%{http_code}:" | tr "n" " ")
$ echo $RETURN_STRING 
123.012.234.201 HTTP_CODE:200:

Then:

IP="${RETURN_STRING%% *}"
$ echo $IP
123.012.234.201
$ HTTP_CODE="${RETURN_STRING##*HTTP_CODE:}"
$ HTTP_CODE="${HTTP_CODE%%:*}"
$ echo $HTTP_CODE 
200

After that, you could check the HTTP_CODE value.

2.. => It’s Ok

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement