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

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


One way of achieving this like,

HTTPS_URL="https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066"CURL_CMD="curl -w httpcode=%{http_code}"# -m, --max-time <seconds> FOR curl operationCURL_MAX_CONNECTION_TIMEOUT="-m 100"# perform curl operationCURL_RETURN_CODE=0CURL_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}"    fifi


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

curl -s -w '%{http_code}\n' 'https://xxxx:1234xxxx@abc.dfghj.com/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 most programs, curl returns a non-zero exit status if it gets an error, so you can test it with if.

if curl 'https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066' > HTML_Outputthen echo "Request was successful"else echo "CURL Failed"fi

I don't know of a way to find out the percentage if the download fails in the middle.