0

I have a url that I need to execute using curl. If the status is 200 then write the response in a temporary file. Now compare this temporary file with another file ("/opt/proc/config/init.txt"). If the temporary file is different then replace content of init.txt with that temporary file. But if status is not 200 then exit with non zero status code with a message.

Below is what I have got. Is there any better or efficient way to do this? Also can this all be done in single line if possible?

URL="some_url"
# store the whole response with the status at the and
response=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST $URL)
# extract the body
new=$(echo $response | sed -e 's/HTTPSTATUS\:.*//g')
# extract the status
status=$(echo $response | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
# print the body
echo "$new"
echo $new > /opt/proc/config/temp.txt

if [ $status -eq 200  ]; then
    if ! cmp /opt/proc/config/init.txt /opt/proc/config/temp.txt > /dev/null 2>&1
    then
      echo different
      mv /opt/proc/config/temp.txt /opt/proc/config/init.txt
    else
      echo same
    fi
else
  echo "Error [HTTP status: $status]"
  rm /opt/proc/config/temp.txt
  exit 1
fi
2
  • Why a single line? If you have a script, you can run that in a single line: ./script.sh.
    – Kusalananda
    Jan 8 '20 at 17:34
  • I mean not just one single line. I am sure above thing can be combined in two different lines very easily. Since we need to grep the status and then write the response in a file and then compare and move the content. But if it cannot be done in multiple single lines then a script will be fine as well.
    – david
    Jan 8 '20 at 17:36
-1

I'm not sure I would have used cmp for comparing the files. Probably I would simply generate a md5 or sha1 fingerprint of each file, and compare the fingerprints. Because you don't care about the details like offsets and line numbers where the two files differ, you just want to know if both files are exactly the same. Anyway I wouldn't worry about performance issues here unless the files are very big.

Why not simply use the -o, --output option to write the downloaded file to disk ?

Rather than parse the response headers with sed or whatever, just use the cURL variables that are available ie %{response_code}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.