Post

Bash - save curl response code and body in variables

Save curl httpcode and response in variables for further processing. Found via https://unix.stackexchange.com/a/572434

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

URL="https://example.com"

response=$(curl --silent --write-out "%{http_code}" $URL)

http_code=$(tail -n1 <<< "$response")  # get the last line
content=$(sed '$ d' <<< "$response")   # get all but the last line which contains the status code

echo "$http_code"
echo "$content"

# do something with the http_code, such as
if [[ "http_code" -ne 201 ]]; then
    echo "Create failed."
    exit 1
fi

Links to the command line options:

This post is licensed under CC BY 4.0 by the author.