Linux commands
Browse topics

Transferring data with curl

Version
unversioned
Review
Draft

Summary#

curl transfers data to or from a URL and writes the response to standard output by default. It handles several protocols, including HTTP, HTTPS and local file:// URLs.

Syntax#

sh
curl -sS --fail -L -o output "$url"
curl -sS -w '%{http_code}\n' -o /dev/null "$url"

-sS hides the progress meter but keeps error messages. -L follows HTTP redirects, -o names the output file and -w prints details after the transfer.

Example#

The example reads local files through file:// URLs and needs no network. Putting -q first makes curl skip its default configuration file.

sh
(
  set -eu
  dir=$(mktemp -d /tmp/devlookup-curl.XXXXXXXXXX)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf '{"status":"ok"}\n' > health.json

  curl -q -sS "file://$dir/health.json"
  curl -q -sS -o copy.json -w 'saved %{size_download} bytes\n' "file://$dir/health.json"
  cmp health.json copy.json
  status=0
  curl -q -sS "file://$dir/missing.json" 2>/dev/null || status=$?
  echo "missing file: exit status $status"
)

Expected output#

Text
{"status":"ok"}
saved 16 bytes
missing file: exit status 37

Common mistakes#

An HTTP response such as 404 or 500 does not make curl fail by default, so a script can save an error page as if it were the file. Add --fail, or --fail-with-body when you also need the response body. Check the destination before using -o, which can overwrite an existing file.

Version applicability#

This entry describes the command from the curl project. --fail-with-body requires curl 7.76.0 or later, and the protocols available depend on how curl was built.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0