Website Vidya
Cloud & DevOpsStep-by-Step Guide

curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests

Learn curl command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests
AI Executive SummaryWebsiteVidya AI

10 min read

Learn curl command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What curl Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Mastering the curl command in linux is a vital competency for software developers, DevOps practitioners, and system administrators. Created by Daniel Stenberg in 1997, curl (Client URL) has evolved into one of the most widely used software packages on Earth, embedded in billions of mobile devices, servers, routers, and container images.

Unlike high-level download utilities that focus exclusively on writing files to disk, curl is designed for granular protocol interaction. By default, curl outputs received data directly to standard output (stdout), allowing seamless composition within Unix pipelines alongside tools like jq, grep, and awk. Whether submitting multipart POST requests to REST APIs, debugging OAuth2 Bearer token authentication, or measuring network latency down to the microsecond, curl provides complete control over every byte sent across the wire.

Underneath the command-line interface lies libcurl, a robust, thread-safe network transfer library supporting HTTP/1.1, HTTP/2, HTTP/3 (QUIC), TLS 1.3 encryption, proxy tunneling, and asynchronous socket multiplexing. Understanding curl's extensive option flags enables engineers to construct reliable, production-ready automation workflows.

Advertisement
curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests — syntax, flags, and practical terminal workflow diagram
curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests — command syntax, key options, and production workflow reference.

What curl Does and When to Use It

Architecturally, curl operates as a stateful client engine built on libcurl's multi-interface. It manages socket creation, DNS resolution caching, TCP three-way handshakes, and cryptographic TLS handshakes through backend crypto providers such as OpenSSL, GnuTLS, or NSS. For modern web services, curl negotiates Application-Layer Protocol Negotiation (ALPN) to establish multiplexed HTTP/2 or HTTP/3 streams over a single connection.

When executing transfers, curl maintains separate internal state buffers for request headers, request bodies, response headers, and response payloads. The write-out mechanism (-w) interfaces with libcurl's internal timer structures, capturing high-resolution timestamps for time_namelookup (DNS resolution), time_connect (TCP handshake), time_appconnect (TLS handshake), time_starttransfer (Time to First Byte / TTFB), and time_total.

At the operating system level, curl interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running curl in cloud instances or Kubernetes worker nodes, combining flags such as -X METHOD, -H HEADER, -d DATA, -i lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The curl utility is packaged in curl across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether curl is installed and inspect which binary path and version your shell resolves:

type -a curl
curl --version 2>/dev/null || man -f curl

# Illustrative output (reviewed against documentation)
curl is /usr/bin/curl
curl (curl)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y curl

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y curl

# Arch Linux
sudo pacman -S --noconfirm curl

# Alpine Linux
sudo apk add --no-cache curl

Command Syntax, Arguments, and Exit Status Codes

curl [OPTIONS] [URL...]

The command syntax follows: curl [OPTIONS] [URL...]. Options alter HTTP verbs (-X GET/POST/PUT/DELETE), inject request headers (-H 'Header: Value'), transmit request bodies (-d 'data'), handle authentication (-u user:pass or -H 'Authorization: Bearer ...'), and format output (-o file, -O, -s, -i, -I).

Crucially, curl does not follow HTTP redirects (301, 302, 307, 308) by default; you must pass -L (--location) to instruct curl to follow the Location response header. To inspect HTTP response headers alongside the payload, pass -i; to retrieve only the response headers without downloading the body, pass -I (HEAD request).

  • 0 — Successful execution; connection completed and data transferred without protocol errors.
  • 6 — Couldn't resolve host; DNS lookup failed for the specified domain name.
  • 7 — Failed to connect to host; target port closed, connection refused, or network unreachable.
  • 28 — Operation timeout; maximum allowed connection or transfer time expired.
  • 35 — SSL/TLS connect error; cipher negotiation failed or protocol handshake rejected.
  • 52 — Server returned nothing; empty reply received on open socket.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-X METHOD--request METHODSpecifies the custom HTTP request method to use (e.g., GET, POST, PUT, DELETE, PATCH).
-H HEADER--header HEADERAdds a custom HTTP header to the request (e.g., -H 'Content-Type: application/json').
-d DATA--data DATASends specified data in an HTTP POST request, automatically setting Content-Type to application/x-www-form-urlencoded.
-i--includeIncludes HTTP response headers in the output alongside the response body.
-I--headFetches HTTP headers only using a HEAD request without downloading the response payload body.
-o FILE--output FILEWrites received output to FILE instead of standard output (stdout).
-O--remote-nameWrites output to a local file named after the remote file component in the URL.
-L--locationFollows HTTP redirects (3xx response codes) until the final destination page is reached.
-s--silentSilent mode; hides progress meter and error messages (often combined with -S to display errors).
-w FORMAT--write-out FORMATDisplays formatted diagnostic metrics (e.g., %{http_code}, %{time_total}) upon completion.

For automated shell scripts and CI/CD pipelines, the industry-standard flag combination is -sSL -w '%{http_code}\n'. Adding -s silences the progress meter, -S preserves error messages on failure, -L follows redirects transparently, and -w outputs the exact HTTP status code for conditional branching.

Advertisement

When debugging REST API endpoints, combining -i with formatted JSON input (-H 'Content-Type: application/json' -d '...') is essential. Seeing both response headers (such as RateLimit-Remaining and Set-Cookie) and the response JSON body allows developers to diagnose API rate-limits and token expiration immediately.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Perform a Simple GET Request to an API Endpoint

Fetch JSON data from a REST API endpoint and pipe the output to jq for pretty-printing.

curl -s https://api.example.com/v1/health | jq .

# Illustrative output (reviewed against documentation)
{
  "status": "healthy",
  "version": "2.4.1",
  "uptime_seconds": 184200
}

The -s flag silences progress output, streaming raw JSON to standard output where jq formats it.

2. Follow HTTP Redirects and Save File to Local Disk

Download a file from a URL that issues HTTP 301/302 redirects, saving it with its remote filename.

curl -L -O https://example.com/latest-release.tar.gz

# Illustrative output (reviewed against documentation)
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 42.1M  100 42.1M    0     0  14.2M      0  0:00:02  0:00:02 --:--:-- 14.2M

The -L option follows the redirect chain to the CDN origin, and -O saves the file as latest-release.tar.gz.

3. Send a POST Request with JSON Body and Headers

Submit a JSON payload to a REST API endpoint with explicit Content-Type headers.

curl -X POST https://api.example.com/v1/servers \
  -H "Content-Type: application/json" \
  -d '{"hostname": "web-01", "role": "frontend", "memory_mb": 4096}'

# Illustrative output (reviewed against documentation)
{"id": 1042, "hostname": "web-01", "created_at": "2026-10-22T21:15:00Z"}

curl sends an HTTP POST with the JSON string as the request payload and prints the server's JSON response.

4. Inspect HTTP Response Headers Without Downloading Body

Send an HTTP HEAD request to inspect server software, caching policies, and TLS certificate metadata.

curl -I https://example.com

# Illustrative output (reviewed against documentation)
HTTP/2 200 
content-type: text/html; charset=UTF-8
server: ECS (dcb/7F3B)
cache-control: max-age=604800
date: Thu, 22 Oct 2026 21:16:00 GMT
content-length: 1256

The -I option fetches only headers, revealing HTTP/2 negotiation, server identification, and caching headers.

5. Authenticate Using Bearer Token Authorization Header

Query a secure microservice using an OAuth2 or JWT Bearer token passed in the Authorization header.

curl -s -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsIn..." https://api.example.com/v1/profile

# Illustrative output (reviewed against documentation)
{"user_id": 842, "username": "sysadmin", "tier": "enterprise"}

The custom Authorization header authenticates the API request securely without passing credentials in the URL query string.

6. Extract HTTP Status Code and Sub-Millisecond Latency Metrics

Use curl's write-out formatting engine to measure DNS resolution, TLS handshake time, and HTTP status code.

curl -s -o /dev/null -w "HTTP Status: %{http_code}\nDNS Lookup:  %{time_namelookup}s\nTCP Connect: %{time_connect}s\nTLS Handshake:%{time_appconnect}s\nTotal Time:  %{time_total}s\n" https://example.com

# Illustrative output (reviewed against documentation)
HTTP Status: 200
DNS Lookup:  0.012450s
TCP Connect: 0.024120s
TLS Handshake:0.048920s
Total Time:  0.082410s

Redirecting payload to /dev/null (-o /dev/null) and using -w extracts high-resolution timing metrics from libcurl's connection timers.

Real-World Workflows, Pipelines, and Shell Automation

Automated API Health and SLA Latency Monitoring Script

Deploy an automated health-check probe that queries an API endpoint, extracts the HTTP status code and response time, and alerts if response times violate SLA limits.

#!/usr/bin/env bash
set -euo pipefail

ENDPOINT="https://api.example.com/v1/health"
MAX_ALLOWED_TIME=0.5

echo "=== Probing API Health: ${ENDPOINT} ==="
METRICS=$(curl -s -o /dev/null -w "%{http_code} %{time_total}" "${ENDPOINT}")

HTTP_CODE=$(echo "${METRICS}" | awk '{print $1}')
RESPONSE_TIME=$(echo "${METRICS}" | awk '{print $2}')

echo "HTTP Status Code: ${HTTP_CODE}"
echo "Total Response Time: ${RESPONSE_TIME}s"

if [ "${HTTP_CODE}" -ne 200 ]; then
  echo "CRITICAL: Endpoint returned unhealthy HTTP status ${HTTP_CODE}!"
  exit 1
fi

if (( $(echo "${RESPONSE_TIME} > ${MAX_ALLOWED_TIME}" | bc -l) )); then
  echo "WARNING: SLA Violation! Response time ${RESPONSE_TIME}s exceeded ${MAX_ALLOWED_TIME}s limit."
  exit 2
fi

echo "SUCCESS: Endpoint is healthy and operating within SLA parameters."

# Illustrative output (reviewed against documentation)
=== Probing API Health: https://api.example.com/v1/health ===
HTTP Status Code: 200
Total Response Time: 0.082s
SUCCESS: Endpoint is healthy and operating within SLA parameters.

This production bash script extracts both the HTTP response code and total latency, validating SLA compliance using floating-point comparisons with bc.

Multi-Part Form Data File Upload with Progress Tracking

Automate binary file uploads to an S3-compatible object store or API endpoint using multipart form-data (-F).

#!/usr/bin/env bash
set -euo pipefail

UPLOAD_URL="https://api.example.com/v1/uploads"
API_KEY="secret-api-key-1042"
FILE_PATH="/tmp/backup_archive.tar.gz"

if [ ! -f "${FILE_PATH}" ]; then
  echo "Error: Upload file ${FILE_PATH} does not exist!"
  exit 1
fi

echo "=== Uploading ${FILE_PATH} to ${UPLOAD_URL} ==="
RESPONSE=$(curl -f -s -S \
  -H "X-API-Key: ${API_KEY}" \
  -F "file=@${FILE_PATH};type=application/gzip" \
  -F "retention_days=30" \
  "${UPLOAD_URL}")

echo "Server Response: ${RESPONSE}"

# Illustrative output (reviewed against documentation)
=== Uploading /tmp/backup_archive.tar.gz to https://api.example.com/v1/uploads ===
Server Response: {"upload_id": "up_84210", "status": "stored", "bytes": 45210984}

The -F flag instructs curl to construct an RFC 7578 multipart/form-data payload, specifying the file path with the @ prefix and custom MIME type.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding curl inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Passing credentials via the command-line flag -u user:password exposes plain-text passwords in the system process table (/proc/[pid]/cmdline), accessible to other unprivileged users on the same host. Pass credentials via configuration files (-K), environment variables, or secure netrc files (~/.netrc).

Using the -k (--insecure) option disables SSL/TLS certificate verification, allowing connections to self-signed or invalid certificates. While occasionally used during local development, never use -k in production pipelines, as it completely disables cryptographic protection against Man-in-the-Middle attacks.

GNU/Linux, BSD, and BusyBox Implementation Differences

Curl is pre-installed across virtually every modern operating system, including all Linux distributions, FreeBSD, OpenBSD, macOS, and Microsoft Windows 10/11 (which includes native curl.exe). Command-line options and behavior are exceptionally consistent across platforms.

The specific protocols and TLS ciphers supported by curl depend on how libcurl was compiled. Run curl -V to inspect available features (such as HTTP2, HTTP3, SSL backend, and GSS-API).

Troubleshooting Common Errors and Diagnostics

curl: (6) Could not resolve host

Root Cause: DNS resolution failed because the domain name does not exist, or the local DNS server is unreachable.

Resolution: Verify network connectivity, check /etc/resolv.conf, or test resolution with nslookup.

nslookup api.example.com

curl: (7) Failed to connect to host: Connection refused

Root Cause: The destination IP is reachable, but the target application daemon is not running or listening on the specified port.

Resolution: Verify that the backend service is running and listening on the expected port with ss or netcat.

nc -zv api.example.com 443

curl: (60) SSL certificate problem: self signed certificate

Root Cause: The server's TLS certificate was issued by an untrusted or self-signed Certificate Authority (CA).

Resolution: Provide the custom CA certificate using --cacert /path/to/ca.pem rather than disabling verification with -k.

curl --cacert /etc/ssl/certs/custom-ca.crt https://internal.example.com

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Add the -L (--location) option: curl -L https://example.com. curl will follow 301, 302, and 307 redirects until reaching the final destination.
Specify the Content-Type header and JSON string with -d: curl -X POST -H 'Content-Type: application/json' -d '{"key":"value"}' https://api.example.com.
Use the uppercase -O flag: curl -O https://example.com/archive.zip. To specify a custom filename, use lowercase -o: curl -o custom.zip https://example.com/archive.zip.
Use silent mode (-s), redirect output to /dev/null (-o /dev/null), and print the code with -w: curl -s -o /dev/null -w '%{http_code}\n' https://example.com.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout