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?

# 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
      echo different
      mv /opt/proc/config/temp.txt /opt/proc/config/init.txt
      echo same
  echo "Error [HTTP status: $status]"
  rm /opt/proc/config/temp.txt
  exit 1
  • Why a single line? If you have a script, you can run that in a single line: ./script.sh.
    – Kusalananda
    Commented Jan 8, 2020 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
    Commented Jan 8, 2020 at 17:36

1 Answer 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}.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .