Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if curl was successful and print a message?

I am trying to do a CURL with an IF Else condition. On success of the call Print a successful message or else Print the call failed.

My Sample Curl would look like:

curl 'https://xxxx:[email protected]/xl_template.get_web_query?id=1035066' > HTML_Output.html

I want to do the same thing using Shell.

Using JavaScript:

if(res.status === 200){console.log("Yes!! The request was successful")}
else {console.log("CURL Failed")}

Also, I see the CURL percentage, but I do not know, how to check the percentage of CURL. Please help.

CURL output CURL output

like image 508
Aditya Chouhan Avatar asked Aug 11 '16 20:08

Aditya Chouhan


2 Answers

You can use the -w (--write-out) option of curl to print the HTTP code:

curl -s -w '%{http_code}\n' 'https://xxxx:[email protected]/xl_template.get_web_query?id=1035066'

It will show the HTTP code the site returns.

Also curl provides a whole bunch of exit codes for various scenarios, check man curl.

like image 162
heemayl Avatar answered Nov 09 '22 00:11

heemayl


One way of achieving this like,

HTTPS_URL="https://xxxx:[email protected]/xl_template.get_web_query?id=1035066"
CURL_CMD="curl -w httpcode=%{http_code}"

# -m, --max-time <seconds> FOR curl operation
CURL_MAX_CONNECTION_TIMEOUT="-m 100"

# perform curl operation
CURL_RETURN_CODE=0
CURL_OUTPUT=`${CURL_CMD} ${CURL_MAX_CONNECTION_TIMEOUT} ${HTTPS_URL} 2> /dev/null` || CURL_RETURN_CODE=$?
if [ ${CURL_RETURN_CODE} -ne 0 ]; then  
    echo "Curl connection failed with return code - ${CURL_RETURN_CODE}"
else
    echo "Curl connection success"
    # Check http code for curl operation/response in  CURL_OUTPUT
    httpCode=$(echo "${CURL_OUTPUT}" | sed -e 's/.*\httpcode=//')
    if [ ${httpCode} -ne 200 ]; then
        echo "Curl operation/command failed due to server return code - ${httpCode}"
    fi
fi
like image 20
Balaji Reddy Avatar answered Nov 08 '22 23:11

Balaji Reddy