Primeros pasos
Peticiones básicas
curl hace peticiones HTTP desde la línea de comandos. Por defecto hace GET. -v muestra salida verbosa, -o guarda en un archivo con nombre, -O conserva el nombre del archivo remoto, -L sigue redirecciones, -I solo obtiene los headers (petición HEAD).
# GET request (default)
curl https://example.com
# with verbose output
curl -v https://example.com
# save output to file
curl -o output.html https://example.com
curl -O https://example.com/file.zip # keep remote filename
# follow redirects
curl -L https://example.com/redirect
# show only headers
curl -I https://example.com
curl --head https://example.comSalida y guardado
-o escribe el body en un archivo con nombre; -O usa el nombre del archivo remoto. --output-dir fija el directorio de destino. -s (silent) suprime el medidor de progreso y los errores — emparéjalo con -S para seguir viendo los errores. Usa -D para volcar los headers a un archivo mientras descartas el body con -o /dev/null.
# print body to stdout (default)
curl https://example.com
# save body to file
curl -o page.html https://example.com
# save with remote filename
curl -O https://example.com/file.zip
# save to specific dir with remote name
curl -O --output-dir /tmp https://example.com/file.zip
# append to file
curl https://example.com >> log.txt
# discard body, keep headers
curl -o /dev/null -D headers.txt https://example.com
# silent (no progress, no errors)
curl -s https://example.comVerboso y headers
-v (verbose) imprime la conversación completa: '>' es la petición, '<' es la respuesta, '*' es información de curl — eso va a stderr, así que stdout queda limpio para el body. -I envía una petición HEAD e imprime los headers. -D vuelca los headers a un archivo o a '-' para stdout; combínalo con -o /dev/null para inspeccionar los headers sin guardar el body.
# verbose: shows request + response, sent to stderr
curl -v https://example.com
# > lines are the request, < lines are the response
# * lines are curl's internal info
# headers only (HEAD request)
curl -I https://example.com
# dump response headers to file
curl -D headers.txt -o body.html https://example.com
# dump headers to stdout, body to file
curl -D - -o body.html https://example.com
# show only response headers (no HEAD)
curl -s -o /dev/null -D - https://example.comSeguir redirecciones
-L sigue las redirecciones HTTP 3xx; por defecto curl sigue hasta 50 saltos (usa --max-redirs para limitar). Las RFC 301/302 normalmente convierten POST en GET — usa --post301/--post302 para conservar el verbo. Por defecto las credenciales no se envían a hosts redirigidos; --location-trusted las envía también a esos hosts (riesgo de seguridad).
# follow 3xx redirects
curl -L https://example.com/old
# limit number of redirects
curl -L --max-redirs 5 https://example.com
# treat redirects as POST (default resends as GET)
curl -L --post301 --post302 https://example.com
# show each hop in a redirect chain
curl -L -v https://short.url/abc 2>&1 | grep -i location
# follow only http/https redirects
curl -L --proto-redir http,https https://example.com
# send credentials only on first request
curl -L --location-trusted -u user:pass https://example.comSintaxis de URL y globbing
curl expande los patrones de 'globbing' de URL: rangos [1-10], listas {a,b,c}, con un :step opcional. Cada expansión es una petición separada. Usa -g (--globoff) para tratar corchetes y llaves literalmente — importante para URLs que contienen arrays JSON o direcciones IPv6 como http://[::1]:8080/.
# range glob: requests file1, file2, file3
curl -O https://example.com/file[1-3].zip
# range with step
curl -O https://example.com/file[1-10:2].zip # 1,3,5,7,9
# list glob: a, b, c
curl -O https://example.com/{a,b,c}.zip
# combined globs
curl -O https://example.com/{v1,v2}/file[1-2].txt
# output each URL as it is fetched
curl -O https://example.com/file[1-3].zip --write-out "%{url} -> %{filename}\n"
# disable globbing (literal brackets/braces)
curl -g "https://example.com/file[1].zip"Ayuda y versión
--version muestra la versión de curl, los protocolos soportados (HTTP, HTTPS, FTP, etc.) y las características compiladas (HTTP2, SSL, brotli). --help all lista todas las opciones — útil cuando recuerdas parte del nombre de un flag. Las características dependen de cómo se compiló curl (por ejemplo, HTTP/3 necesita una compilación especial).
# version and supported features
curl --version
# short help (one-line per option)
curl --help
# long help (all options with details)
curl --help all
# search help for a keyword
curl --help all | grep -i cookie
# list supported protocols
curl --version | head -1
# check if a feature is built in
curl --version | grep -i http2Verbos HTTP
Peticiones GET
GET es el verbo por defecto. Entrecomilla siempre las URLs que contengan & o ? para que el shell no las envíe a segundo plano ni las expanda. -X fija el verbo explícitamente, pero suele ser innecesario para GET. Para APIs, fija Accept para negociar el formato de la respuesta.
# simple GET (default method)
curl https://api.example.com/data
# GET with query string
curl "https://api.example.com/search?q=curl&page=2"
# explicit method
curl -X GET https://example.com
# GET with headers
curl -H "Accept: application/json" https://api.example.com/data
# GET with auth
curl -u user:pass https://api.example.com/secretPeticiones POST
Enviar -d cambia automáticamente el verbo a POST, así que -X POST es redundante (pero inofensivo y aclaratorio). Para hacer POST de un archivo, usa -d @filename (la @ lee el archivo). El Content-Type por defecto de -d es application/x-www-form-urlencoded; sobrescríbelo con -H para JSON.
# POST with form data (application/x-www-form-urlencoded)
curl -X POST -d "name=Alice&age=30" https://api.example.com/users
# -d implies POST, so -X is optional
curl -d "name=Alice" https://api.example.com/users
# POST with no body
curl -X POST https://api.example.com/trigger
# POST JSON
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"Alice"}' https://api.example.com/users
# POST with data from a file
curl -X POST -d @form.txt https://api.example.com/usersPUT y PATCH
PUT reemplaza un recurso completo; PATCH aplica una actualización parcial. Ambos requieren -X porque curl no tiene atajo con -d para ellos. -T (upload-file) transmite un archivo como body de la petición y es ideal para subidas PUT. Usa --data-binary en lugar de -d para evitar que se recorten los saltos de línea al enviar archivos crudos.
# PUT (replace entire resource)
curl -X PUT -H "Content-Type: application/json" \
-d '{"name":"Alice","age":31}' \
https://api.example.com/users/1
# PATCH (partial update)
curl -X PATCH -H "Content-Type: application/json" \
-d '{"age":32}' \
https://api.example.com/users/1
# PUT a file as body
curl -X PUT --data-binary @config.json \
-H "Content-Type: application/json" \
https://api.example.com/config
# PUT with upload file
curl -X PUT -T localfile.txt https://example.com/remote.txtDELETE
DELETE elimina un recurso. La mayoría de APIs requieren autenticación, así que incluye -u o un header Authorization. Algunas APIs aceptan un body (motivo, flags de cascada) — añade -d y un header Content-Type. Usa -w '%{http_code}' para comprobar el resultado: 204 (No Content) y 200 son éxitos típicos.
# delete a resource
curl -X DELETE https://api.example.com/users/1
# delete with auth
curl -X DELETE -H "Authorization: Bearer TOKEN" \
https://api.example.com/users/1
# delete with confirmation check
curl -X DELETE -w "%{http_code}" -o /dev/null -s \
https://api.example.com/users/1
# delete with request body (some APIs require it)
curl -X DELETE -H "Content-Type: application/json" \
-d '{"reason":"spam"}' \
https://api.example.com/users/1HEAD y OPTIONS
-I envía una petición HEAD (solo headers, sin body) — útil para comprobar tamaño (Content-Length), tipo (Content-Type) y última modificación sin descargar. OPTIONS revela los verbos permitidos (el header Allow) y lo usan los navegadores para el preflight de CORS. Añade los headers Origin y Access-Control-Request-Method para simular un preflight real.
# HEAD: headers only, no body
curl -I https://example.com
curl --head https://example.com
# OPTIONS: discover allowed methods
curl -X OPTIONS https://api.example.com/users
# OPTIONS with CORS preflight headers
curl -X OPTIONS \
-H "Origin: https://mysite.com" \
-H "Access-Control-Request-Method: POST" \
https://api.example.com/users
# check allowed methods from Allow header
curl -X OPTIONS -s -D - -o /dev/null https://api.example.com | grep -i allowHeaders
Fijar headers (-H)
-H (--header) añade un header de petición. Repite -H para varios headers. Un punto y coma final (X-Empty;) envía un valor vacío. @headers.txt lee los headers de un archivo (un 'Name: value' por línea) — práctico para mantener los tokens de Authorization fuera del historial del shell.
# single header
curl -H "Accept: application/json" https://api.example.com/data
# multiple headers
curl -H "Accept: application/json" \
-H "Authorization: Bearer TOKEN" \
-H "X-Custom: value" \
https://api.example.com/data
# header with empty value
curl -H "X-Empty;" https://example.com
# headers from a file (one per line)
curl -H @headers.txt https://example.com
# Content-Type for POST
curl -X POST -H "Content-Type: application/json" \
-d '{"a":1}' https://api.example.comHeaders comunes
Los headers más comunes: Accept le dice al servidor qué formato quieres; Content-Type describe el body de la petición; Authorization lleva las credenciales. --compressed pide a curl solicitar respuestas comprimidas (gzip, br) y descomprimirlas automáticamente, así no tienes que manejar la codificación a mano.
# Accept: negotiate response format
curl -H "Accept: application/json" https://api.example.com
curl -H "Accept: text/html" https://example.com
# Content-Type: describe request body
curl -H "Content-Type: application/json" -d '{"a":1}' https://api.example.com
curl -H "Content-Type: application/x-www-form-urlencoded" -d "a=1" https://api.example.com
# Authorization: credentials
curl -H "Authorization: Bearer TOKEN" https://api.example.com
# Accept-Encoding: ask for compression
curl -H "Accept-Encoding: gzip, br" --compressed https://example.com
# Cache-Control
curl -H "Cache-Control: no-cache" https://api.example.comUser-Agent
Algunos servidores bloquean el User-Agent por defecto de curl. -A (--user-agent) lo fija; un -A vacío lo elimina por completo. La forma larga es -H 'User-Agent: ...'. Muchos sitios que bloquean scraping comprueban firmas de navegador reales, así que a menudo se exige un UA de navegador realista.
# default User-Agent looks like: curl/8.7.1
curl -v https://example.com 2>&1 | grep -i user-agent
# set a custom User-Agent
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://example.com
curl -H "User-Agent: MyBot/1.0" https://example.com
# empty User-Agent
curl -A "" https://example.com
# fake a real browser (some sites require it)
curl -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) \
AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/120.0 Safari/537.36" https://example.com
# per-site default via config
# user-agent = "MyBot/1.0" in ~/.curlrcReferer y Host
-e (--referer) fija el header Referer. Sobrescribir Host es esencial al probar hosts virtuales por IP: el servidor elige el sitio correcto según Host. Los endpoints conscientes de CORS a menudo exigen Origin; X-Forwarded-For/Proto simulan peticiones tras un proxy o balanceador.
# set Referer header
curl -H "Referer: https://google.com" https://example.com/page
curl -e https://google.com https://example.com/page
# set Host header (override DNS)
curl -H "Host: api.example.com" https://192.168.1.10/users
# combined: test a vhost by IP with custom Host
curl -H "Host: api.example.com" \
-H "X-Forwarded-Proto: https" \
http://10.0.0.5/health
# Origin header (for CORS/POST forms)
curl -H "Origin: https://mysite.com" \
-X POST -d "x=1" https://api.example.com/form
# X-Forwarded-For (debugging proxies)
curl -H "X-Forwarded-For: 1.2.3.4" https://api.example.comEliminar headers
Proporcionar -H 'Header-Name:' (con dos puntos pero sin valor) indica a curl que no envíe valor para ese header, eliminando efectivamente un header por defecto como User-Agent o Accept-Encoding. curl reemplaza un header si especificas de nuevo el mismo nombre en lugar de enviar duplicados. Útil para enviar la petición mínima posible.
# remove a header by giving it no value
curl -H "User-Agent:" https://example.com
# remove Accept-Encoding (disable compression)
curl -H "Accept-Encoding:" https://example.com
# remove all auto-added headers and send minimal request
curl -H "Host:" -H "User-Agent:" -H "Accept:" https://example.com
# prevent curl from adding Accept-Encoding
curl --no-keepalive https://example.com
# replace a default header instead of adding a duplicate
# (curl replaces, doesn't duplicate, when -H name matches)
curl -H "Accept: text/plain" https://example.comDatos POST y formularios
Datos de formulario (-d)
-d (--data) envía datos de formulario con codificación URL y cambia el verbo a POST. Varios flags -d se unen con &. -d recorta los espacios y saltos de línea al inicio/final; --data-binary los conserva; --data-raw desactiva por completo la característica de @archivo (así un valor literal que empiece por @ se envía tal cual).
# URL-encoded form data
curl -d "name=Alice&age=30" https://api.example.com/form
# explicit POST (same result; -d implies POST)
curl -X POST -d "name=Alice" https://api.example.com/form
# multiple -d are joined with &
curl -d "name=Alice" -d "age=30" https://api.example.com/form
# -d strips newlines; use --data-binary to preserve them
curl --data-binary "line1\nline2" https://api.example.com
# raw data, no content-type added
curl --data-raw "name=Alice&age=30" https://api.example.com
# default Content-Type: application/x-www-form-urlencoded
curl -v -d "a=1" https://api.example.com 2>&1 | grep -i content-typeCodificación URL
--data-urlencode codifica en porcentaje el valor (o el name=value completo), así no tienes que codificar manualmente espacios, &, = o no ASCII. Con name@file, el contenido del archivo se codifica como valor. Úsalo siempre con datos proporcionados por el usuario para no romper la estructura del formulario.
# spaces and special chars must be encoded
curl -d "name=Alice%20Smith" https://api.example.com
curl -d "name=Alice+Smith" https://api.example.com
# --data-urlencode encodes the value for you
curl --data-urlencode "name=Alice Smith" https://api.example.com
curl --data-urlencode "[email protected]" https://api.example.com
# encode name=value pair (both encoded)
curl --data-urlencode "name=Alice & Bob" https://api.example.com
# encode only the value after =, with explicit content-type
curl --data-urlencode "query=SELECT * FROM users" \
-H "Content-Type: application/x-www-form-urlencoded" \
https://api.example.com/search
# encode content of a file
curl --data-urlencode [email protected] https://api.example.comDatos binarios
--data-binary envía un archivo byte a byte (conservando saltos de línea y bytes nulos), a diferencia de -d que los recorta. -T transmite el archivo en streaming, así que el uso de memoria se mantiene bajo en subidas grandes. Para enviar datos precomprimidos, pásalos por pipe con -H 'Content-Encoding: gzip' — el servidor debe soportarlo; si no, usa Transfer-Encoding: chunked.
# send a binary file as the body
curl --data-binary @image.png https://api.example.com/upload
# upload with explicit content type
curl --data-binary @image.png \
-H "Content-Type: image/png" \
https://api.example.com/upload
# raw bytes (no @ expansion, no stripping)
curl --data-raw "$(printf '\x00\x01\x02')" https://api.example.com
# stream a large file without buffering in memory
curl -T bigfile.iso https://api.example.com/upload
# send gzipped body
gzip -c data.json | curl --data-binary @- \
-H "Content-Encoding: gzip" \
-H "Content-Type: application/json" \
https://api.example.com/dataLeer de un archivo (@file)
-d @file lee el body de la petición de un archivo (la @ activa la lectura de archivo). --data-binary @file conserva los bytes. -d @- lee de stdin — perfecto para encadenar jq, curl u otras transformaciones por pipe. Si un valor literal empieza por @ y no quieres expansión de archivo, usa --data-raw.
# read body from a file
curl -d @data.txt https://api.example.com/form
# read JSON body from a file
curl -H "Content-Type: application/json" \
-d @payload.json https://api.example.com
# binary-safe file read
curl --data-binary @image.png https://api.example.com/upload
# read from stdin
echo '{"a":1}' | curl -d @- https://api.example.com
# pipe through curl (transform then send)
jq '{name, age}' input.json | \
curl -H "Content-Type: application/json" -d @- https://api.example.com
# file name starting with @ (use --data-raw)
curl --data-raw "@mention" https://api.example.comContent-Type y formularios
Haz coincidir siempre Content-Type con el formato del body: application/x-www-form-urlencoded (por defecto para -d), application/json (con -H), multipart/form-data (fijado automáticamente por -F), text/xml para SOAP. Añadir charset=utf-8 es buena práctica para datos no ASCII. Las discrepancias hacen que los servidores rechacen o malinterpreten el body.
# default for -d: application/x-www-form-urlencoded
curl -d "name=Alice" https://api.example.com
# JSON body
curl -H "Content-Type: application/json" \
-d '{"name":"Alice"}' https://api.example.com
# multipart form (file upload, see File Upload section)
curl -F "[email protected]" https://api.example.com/upload
# text/plain body
curl -H "Content-Type: text/plain" -d "hello" https://api.example.com
# XML body (SOAP)
curl -H "Content-Type: text/xml" \
-d '<?xml version="1.0"?><env:Envelope/>' \
https://api.example.com/soap
# set charset explicitly
curl -H "Content-Type: application/json; charset=utf-8" \
-d '{"name":"éàç"}' https://api.example.comPeticiones JSON
POST JSON básico
Las peticiones JSON necesitan -H 'Content-Type: application/json' más -d con una cadena JSON. Usa comillas simples alrededor del JSON para que el shell no toque las comillas dobles internas. Pasa la respuesta por pipe con jq '.' para una salida legible, o jq '.field' para extraer un valor concreto.
# JSON POST request
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Alice","age":30}' \
https://api.example.com/users
# -d already implies POST, so -X is optional
curl -H "Content-Type: application/json" \
-d '{"name":"Alice"}' \
https://api.example.com/users
# ask for JSON back
curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{"name":"Alice"}' \
https://api.example.com/users
# pretty-print the JSON response (pipe to jq)
curl -s -H "Accept: application/json" \
https://api.example.com/users/1 | jq .JSON desde archivo
Para JSON complejo, guárdalo en un archivo .json y usa -d @file (o --data-binary @file para conservar los bytes exactos, incluidos los saltos de línea finales). Encadenar con pipe jq -n te permite construir JSON programáticamente sin escapados delicados. Valida siempre con jq . primero — un error de sintaxis desperdicia una petición.
# POST JSON body from a file
curl -H "Content-Type: application/json" \
-d @payload.json https://api.example.com/users
# binary-safe (preserves exact bytes)
curl -H "Content-Type: application/json" \
--data-binary @payload.json https://api.example.com/users
# generate JSON with jq, then POST
jq -n '{name: "Alice", age: 30}' | \
curl -H "Content-Type: application/json" \
-d @- https://api.example.com/users
# validate JSON before sending
jq . payload.json && \
curl -H "Content-Type: application/json" \
-d @payload.json https://api.example.com/users
# send a JSON array
curl -H "Content-Type: application/json" \
-d '[{"id":1},{"id":2}]' https://api.example.com/batchJSON con variables
Interpolar variables en cadenas JSON se rompe con comillas y caracteres especiales. El patrón seguro es jq --arg/--argjson: construye JSON válido y escapa los valores correctamente. --arg para cadenas, --argjson para números/booleanos. Para secretos, prefiere un archivo de headers (-H @file) antes que argumentos de línea de comandos para evitar fugas vía ps.
# interpolate a shell variable into JSON (risky for special chars)
NAME="Alice"
curl -H "Content-Type: application/json" \
-d "{\"name\":\"$NAME\"}" https://api.example.com
# safer: build JSON with jq
NAME="Alice"
jq -n --arg name "$NAME" '{name: $name}' | \
curl -H "Content-Type: application/json" -d @- https://api.example.com
# multiple variables
NAME="Alice"; AGE=30
jq -n --arg name "$NAME" --argjson age "$AGE" \
'{name: $name, age: $age}' | \
curl -H "Content-Type: application/json" -d @- https://api.example.com
# read secret from env, hide from ps
TOKEN="$API_TOKEN" curl -H "Authorization: Bearer $API_TOKEN" \
-d '{"x":1}' https://api.example.comPeticiones GraphQL
GraphQL usa un único endpoint POST con un body JSON que contiene una cadena 'query' y unas 'variables' opcionales. Escribir la query en línea exige escapar las comillas dobles internas, así que guarda las queries complejas en un archivo .json y usa -d @file. La introspección (la query __schema) lista los tipos de la API y es genial para explorar.
# GraphQL query as JSON body
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer TOKEN" \
-d '{"query":"{ user(id:1) { name email } }"}' \
https://api.example.com/graphql
# query with variables
curl -X POST \
-H "Content-Type: application/json" \
-d '{"query":"query($id:Int!){ user(id:$id){name} }","variables":{"id":1}}' \
https://api.example.com/graphql
# query from a file (multi-line, no escaping pain)
curl -X POST \
-H "Content-Type: application/json" \
-d @query.json https://api.example.com/graphql
# introspection: list all types
curl -s -X POST -H "Content-Type: application/json" \
-d '{"query":"{ __schema { types { name } } }"}' \
https://api.example.com/graphql | jqNegociación de contenido
Accept negocia el formato de la respuesta; muchas APIs REST devuelven JSON por defecto pero soportan alternativas XML o CSV. --compressed pide gzip/brotli y descomprime automáticamente. Las APIs suelen versionarse vía Accept (por ejemplo, GitHub: application/vnd.github+json). Comprueba el Content-Type real que devuelve el servidor para confirmar que la negociación funcionó.
# request JSON
curl -H "Accept: application/json" https://api.example.com/users
# request XML
curl -H "Accept: application/xml" https://api.example.com/users
# request a specific version
curl -H "Accept: application/vnd.api+json; version=2" \
https://api.example.com/users
# request anything (default is */*)
curl -H "Accept: */*" https://example.com
# request compression and auto-decompress
curl --compressed -H "Accept-Encoding: gzip, br" https://example.com
# inspect what the server actually returns
curl -s -o /dev/null -D - https://api.example.com/users | grep -i content-typeSubida de archivos
Subida multipart (-F)
-F (--form) construye una petición multipart/form-data — el estándar para subir archivos. -F file=@path lee el archivo. Añade ;filename= para sobrescribir el nombre que ve el servidor, y ;type= para fijar el Content-Type de la parte. Varios archivos bajo el mismo nombre de campo (con [] en muchos frameworks) necesitan varios flags -F.
# upload a file as a multipart form field
curl -F "[email protected]" https://api.example.com/upload
# -F sets POST + multipart/form-data automatically
# the @ prefix reads the file
# add a text field alongside the file
curl -F "[email protected]" -F "description=My photo" \
https://api.example.com/upload
# rename the uploaded file (server sees "avatar.jpg")
curl -F "[email protected];filename=avatar.jpg" \
https://api.example.com/upload
# set explicit content-type for the file part
curl -F "[email protected];type=image/jpeg" \
https://api.example.com/upload
# upload multiple files in one field
curl -F "[email protected]" -F "[email protected]" \
https://api.example.com/uploadMúltiples archivos y campos
Los formularios multipart pueden mezclar archivos y campos de texto. Usa [] en los nombres de campo para subidas estilo array (frameworks como Rails/PHP los parsean a arrays). Un campo puede llevar JSON fijando ;type=application/json — el servidor lo lee como datos estructurados y no como archivo. curl no puede subir directorios de forma nativa; taréalos primero.
# upload two files and a caption
curl -F "[email protected]" \
-F "[email protected]" \
-F "caption=Summer trip" \
https://api.example.com/gallery
# array-style field names (PHP/Rails style)
curl -F "files[][email protected]" -F "files[][email protected]" \
https://api.example.com/upload
# send a file's contents as a regular text field
curl -F "[email protected];type=application/json" \
https://api.example.com/upload
# mix file and JSON fields
curl -F "[email protected]" \
-F "options={\"priority\":\"high\"};type=application/json" \
https://api.example.com/upload
# upload a directory as a tar (workaround)
tar -cf - mydir/ | curl -F "tar=@-;filename=dir.tar" \
https://api.example.com/uploadSubida en streaming (-T)
-T (--upload-file) usa PUT y transmite el archivo en streaming, así que la memoria se mantiene plana incluso en subidas enormes — mucho mejor que -d @file para grandes volúmenes. -T - lee de stdin. -C - reanuda una transferencia interrumpida. Con una barra final en la URL, curl añade el nombre del archivo local (como un PUT HTTP espejo).
# upload a file with PUT (streaming, low memory)
curl -T localfile.txt https://example.com/upload/remote.txt
# upload to a URL with the local filename
curl -T localfile.txt https://example.com/upload/
# stream from stdin (pipe into PUT body)
cat data.json | curl -T - https://api.example.com/data
# upload with authentication
curl -T file.zip -u user:pass \
https://example.com/upload/file.zip
# upload with progress bar
curl -T bigfile.iso --progress-bar \
https://example.com/upload/bigfile.iso
# resume an interrupted upload
curl -T bigfile.iso -C - https://example.com/upload/bigfile.isoSubida con progreso
Por defecto curl muestra un medidor de progreso en stderr. --progress-bar cambia a una barra más simple. -s (silent) lo oculta; añade S (-sS) para seguir viendo los errores. La información de progreso va a stderr, así que stdout (el body) queda limpio — útil al encadenar por pipe. Usa -w con %{size_upload} y %{time_total} para un resumen de una línea.
# default progress meter (terminal)
curl -T file.zip https://example.com/upload
# simple progress bar
curl -T file.zip --progress-bar https://example.com/upload
# no progress at all (silent)
curl -T file.zip -s https://example.com/upload
# show progress but only errors (silent + show-error)
curl -T file.zip -sS https://example.com/upload
# custom progress with --write-out
curl -T file.zip -w "Uploaded %{size_upload} bytes in %{time_total}s\n" \
-o /dev/null https://example.com/upload
# redirect progress to stderr, body to file
curl -T file.zip --progress-bar 2> progress.log \
-o response.txt https://example.com/uploadCampos y tipos de subida
curl adivina el tipo MIME a partir de la extensión del archivo. Sobrescríbelo con ;type=. La opción ;filename= cambia lo que ve el servidor, útil para nombres saneados. El prefijo < lee el contenido de un archivo en un campo de texto (en lugar de enviarlo como archivo) — práctico cuando la API espera una cadena pero tienes los datos en un archivo.
# specify MIME type explicitly
curl -F "[email protected];type=text/csv" https://api.example.com/import
# let curl guess from the extension (default)
curl -F "[email protected]" https://api.example.com/upload
# force generic type
curl -F "[email protected];type=application/octet-stream" \
https://api.example.com/upload
# send a file with a custom filename visible to server
curl -F "upload=@/tmp/abc123;filename=report.pdf;type=application/pdf" \
https://api.example.com/upload
# send a string as if it were a file
curl -F "file=hello world" https://api.example.com/upload
# send a string as a file with a filename
curl -F "file=<inline.txt" https://api.example.com/uploadAutenticación
Basic auth (-u)
-u (--user) envía la autenticación HTTP Basic (user:pass codificado en base64). Omite la contraseña para que se te pida (más seguro — la mantiene fuera del historial del shell). --netrc lee las credenciales de ~/.netrc para que nunca aparezcan en la línea de comandos. Basic es inseguro sobre HTTP plano; usa siempre HTTPS. Cualquiera con acceso al shell puede ver los argumentos de -u vía ps.
# HTTP Basic authentication
curl -u user:pass https://api.example.com/secret
curl --user user:pass https://api.example.com/secret
# prompt for password (don't put it on the command line)
curl -u user https://api.example.com/secret
# basic auth with explicit method (curl picks the safest by default)
curl -u user:pass --basic https://api.example.com/secret
# use a .netrc file instead of -u
echo "machine example.com login user password pass" > ~/.netrc
curl --netrc https://example.com/secret
# base64-encode credentials manually (equivalent)
curl -H "Authorization: Basic $(echo -n user:pass | base64)" \
https://api.example.com/secretToken Bearer
Los tokens Bearer (OAuth2, JWT) van en el header Authorization. Evita poner tokens en la línea de comandos — ps los expone a otros usuarios. Léelos de un archivo (-H @file) o de una variable de entorno, y usa un archivo de headers para valores sensibles. El fragmento de refresh-token muestra el flujo estándar OAuth2 de client-credentials.
# Bearer token (OAuth2 / JWT)
curl -H "Authorization: Bearer ACCESS_TOKEN" \
https://api.example.com/protected
# token from an environment variable
curl -H "Authorization: Bearer $TOKEN" \
https://api.example.com/protected
# token from a file (avoids shell history and ps)
curl -H "Authorization: Bearer $(cat ~/.token)" \
https://api.example.com/protected
# headers from a file (cleanest for secrets)
echo "Authorization: Bearer $TOKEN" > /tmp/hdr.txt
curl -H @/tmp/hdr.txt https://api.example.com/protected
rm /tmp/hdr.txt
# refresh token flow (simplified)
TOKEN=$(curl -s -u client:secret -d "grant_type=refresh_token" \
-d "refresh_token=$REFRESH" \
https://auth.example.com/token | jq -r .access_token)
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/dataAPI key en el header
Las API keys aparecen en headers personalizados (X-API-Key, X-Client-Id) o como parámetros de query. Las query strings se filtran en los logs del servidor y en el historial del navegador, así que prefiere los headers. Para AWS, --aws-sigv4 firma la petición con tus claves access/secret. GitHub usa Bearer con un personal access token (ghp_...).
# API key in a custom header (varies by service)
curl -H "X-API-Key: abc123" https://api.example.com/data
# API key as a query parameter
curl "https://api.example.com/data?api_key=abc123"
# GitHub personal access token
curl -H "Authorization: Bearer ghp_TOKEN" \
https://api.github.com/user
# AWS-style signature v4 (use the AWS CLI or aws-sigv4)
curl --aws-sigv4 "aws:amz:us-east-1:service" \
-u "ACCESS:SECRET" https://service.amazonaws.com/
# multiple keys
curl -H "X-API-Key: abc123" \
-H "X-Client-Id: my-app" \
https://api.example.com/dataArchivos netrc
--netrc lee las credenciales de ~/.netrc, que mapea hosts a pares login/password. El archivo debe tener chmod 600 o curl se niega a usarlo. --netrc-file apunta a una ubicación personalizada. La entrada 'default' se aplica a cualquier host sin una entrada machine específica. Es la forma más limpia de mantener los secretos fuera de la línea de comandos.
# ~/.netrc stores credentials per host
# format:
# machine api.example.com
# login alice
# password secret
# machine github.com
# login alice
# password ghp_TOKEN
# use netrc automatically
curl --netrc https://api.example.com/data
# use a custom netrc file
curl --netrc-file ~/.netrc.work https://api.example.com/data
# ignore netrc for this request
curl --netrc-optional -u user:pass https://api.example.com/data
# secure the file (required by curl on some systems)
chmod 600 ~/.netrc
# machine + default for any host
# default
# login anonymous
# password guestDigest y NTLM
Basic envía las credenciales en texto plano (sobre HTTPS está bien). Digest envía un hash, nunca la contraseña. NTLM y Negotiate manejan el SSO de Windows/Kerberos. --anyauth deja que curl elija según el header WWW-Authenticate del servidor. El servidor debe soportar el verbo; -v muestra qué desafíos emite.
# digest authentication (challenge-response, more secure than Basic)
curl -u user:pass --digest https://api.example.com/secret
# NTLM (Windows auth)
curl -u user:pass --ntlm https://intranet.example.com/
# negotiate (Kerberos/SPNEGO)
curl -u user:pass --negotiate https://intranet.example.com/
# anyauth: let curl pick the method
curl -u user:pass --anyauth https://api.example.com/secret
# specify the service principal for negotiate
curl -u user:pass --negotiate --service-name HTTP/intranet.example.com \
https://intranet.example.com/
# show which method the server requested
curl -v -u user:pass --anyauth https://api.example.com 2>&1 | grep -i www-authenticateOAuth y tokens
OAuth2 tiene varios tipos de grant: client_credentials (servidor a servidor), authorization_code (tras un login en navegador), password (herencia). El endpoint de token devuelve un access_token (y a menudo un refresh_token); usa el access_token como header Bearer en las peticiones siguientes. Las contraseñas de app (GitLab, GitHub) funcionan con -u y evitan las restricciones de 2FA.
# OAuth2 client credentials grant
curl -u client_id:client_secret \
-d "grant_type=client_credentials" \
-d "scope=read write" \
https://auth.example.com/oauth/token
# OAuth2 authorization code (after browser redirect)
curl -d "grant_type=authorization_code" \
-d "code=AUTH_CODE" \
-d "redirect_uri=https://app.example.com/callback" \
-u client_id:client_secret \
https://auth.example.com/oauth/token
# OAuth2 password grant (deprecated but still seen)
curl -d "grant_type=password" \
-d "username=user" -d "password=pass" \
-u client_id:client_secret \
https://auth.example.com/oauth/token
# use the access token
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
https://api.example.com/me
# basic auth with username and app password (e.g., GitLab)
curl -u "user:app_password" https://gitlab.example.com/api/v4/userProxy
Proxy HTTP/HTTPS
-x (--proxy) enruta la petición a través de un proxy. Las variables de entorno http_proxy/https_proxy/no_proxy se respetan automáticamente. Para objetivos HTTPS a través de un proxy HTTP, curl usa CONNECT para tunelar. Fija no_proxy para saltarte el proxy en hosts internos — separado por comas, con un punto inicial que significa subdominios.
# use a proxy for all requests
curl -x http://proxy.example.com:8080 https://example.com
curl --proxy http://proxy.example.com:8080 https://example.com
# HTTPS proxy (proxy connection itself is TLS)
curl -x https://proxy.example.com:8443 https://example.com
# proxy via environment variable
export https_proxy=http://proxy.example.com:8080
curl https://example.com
# proxy for a specific scheme only
curl --proxy http://proxy:8080 http://example.com
curl --proxy https://secure-proxy:8443 https://example.com
# bypass proxy for specific hosts
export no_proxy="localhost,127.0.0.1,.internal.example.com"
curl https://internal.example.com # direct, no proxyProxy SOCKS
SOCKS5 es agnóstico al protocolo, así que tunela HTTP, HTTPS y más. --socks5-hostname hace que el proxy resuelva el DNS (útil para alcanzar hosts que tu máquina no puede resolver). Un truco común: ssh -D 1080 crea un proxy SOCKS local que tunela el tráfico a través de un servidor SSH remoto — genial para navegar con seguridad en redes no confiables.
# SOCKS5 proxy
curl -x socks5://proxy.example.com:1080 https://example.com
curl --socks5 proxy.example.com:1080 https://example.com
# SOCKS5 with local DNS resolution (server resolves)
curl --socks5-hostname proxy.example.com:1080 https://example.com
# SOCKS4 proxy
curl --socks4 proxy.example.com:1080 https://example.com
# SSH tunnel as a SOCKS proxy (run separately)
# ssh -D 1080 user@remote -N
curl -x socks5://localhost:1080 https://example.com
# SOCKS proxy with authentication
curl -x socks5://user:[email protected]:1080 https://example.comAutenticación de proxy
Los proxies suelen exigir autenticación. -U (--proxy-user) proporciona credenciales; --proxy-ntlm/--proxy-digest/--proxy-anyauth eligen el esquema. Incrustar user:pass en la URL de -x es equivalente. Para NTLM (proxies corporativos de Windows), --proxy-ntlm maneja el handshake de varios pasos. -U user (sin contraseña) pregunta interactivamente.
# proxy with username/password
curl -x http://user:[email protected]:8080 https://example.com
# separate proxy auth flag
curl -x http://proxy.example.com:8080 -U user:pass https://example.com
curl --proxy-user user:pass -x http://proxy.example.com:8080 https://example.com
# prompt for proxy password
curl -U user -x http://proxy.example.com:8080 https://example.com
# NTLM-authenticated proxy
curl -U user:pass --proxy-ntlm \
-x http://proxy.example.com:8080 https://example.com
# digest-authenticated proxy
curl -U user:pass --proxy-digest \
-x http://proxy.example.com:8080 https://example.com
# anyauth for proxy
curl -U user:pass --proxy-anyauth \
-x http://proxy.example.com:8080 https://example.comSin proxy y bypass
--noproxy (o la variable no_proxy) lista los hosts que se saltan el proxy. Un punto inicial significa 'este dominio y cada uno de sus subdominios'. '*' salta el proxy sin excepción. Los rangos CIDR funcionan en curl reciente. Es esencial cuando un proxy externo no puede alcanzar los hosts corporativos internos.
# bypass proxy for specific hosts
curl --noproxy "localhost,127.0.0.1,.internal.com" \
-x http://proxy:8080 https://example.com
# via environment variable
export no_proxy="localhost,127.0.0.1,.internal.com,10.0.0.0/8"
curl https://internal.com # direct
# wildcard match for a domain and all subdomains
export no_proxy=".example.com"
curl https://api.example.com # bypasses proxy
# disable proxy entirely for one request
curl --noproxy "*" -x http://proxy:8080 https://example.com
# ignore *_proxy env vars for one request
curl --noproxy "*" https://example.com
# CIDR ranges (curl 7.86+)
export no_proxy="192.168.0.0/16,10.0.0.0/8"Headers de proxy y tunneling
--proxy-header añade headers dirigidos al propio proxy (como Proxy-Authorization), no reenviados al destino. -p (--proxytunnel) fuerza a curl a usar CONNECT incluso para HTTP plano (normalmente CONNECT solo se usa para HTTPS). Es útil cuando el proxy intercepta el HTTP plano y quieres un túnel extremo a extremo.
# add a header sent only to the proxy (not the target)
curl -x http://proxy:8080 \
--proxy-header "Proxy-Authorization: Bearer xyz" \
https://example.com
# custom header to proxy + normal header to target
curl -x http://proxy:8080 \
--proxy-header "X-Proxy-Tag: abc" \
-H "X-Target-Tag: def" \
https://example.com
# force CONNECT tunneling even for HTTP
curl -p -x http://proxy:8080 http://example.com
curl --proxytunnel -x http://proxy:8080 http://example.com
# inspect the CONNECT request to the proxy
curl -v -x http://proxy:8080 https://example.com 2>&1 | grep -i connect
# disable proxy tunneling (send HTTP directly through proxy)
curl --proxytunnel -p -x http://proxy:8080 http://example.comSSL/TLS
Saltar verificación (--insecure)
-k (--insecure) salta la verificación de certificados — úsalo solo para certificados self-signed de desarrollo, nunca en producción, ya que permite ataques MITM. Por defecto se verifican tanto la cadena de certificados como el hostname. --resolve permite fijar una IP manteniendo el Host/SNI correcto — útil para probar un backend concreto detrás de un balanceador.
# skip certificate verification (DANGEROUS)
curl -k https://self-signed.example.com
curl --insecure https://self-signed.example.com
# verify normally (default)
curl https://example.com
# show the cert chain
curl -v https://example.com 2>&1 | grep -E "SSL|cert"
# only verify the cert, not the hostname
curl --insecure https://example.com # both off
# (no built-in flag to verify cert but skip hostname;
# use a custom CA bundle instead)
# connect to a host with a mismatched certificate
curl -k --resolve example.com:443:1.2.3.4 https://example.com
# debug TLS handshake
curl -v https://example.com 2>&1 | grep -E "TLS|SSL|cert|cipher"Certificados de cliente
El TLS mutuo (mTLS) requiere tanto un certificado de cliente (--cert) como su clave privada (--key). PEM es el formato por defecto; --cert-type P12 maneja paquetes PKCS#12. --pass proporciona la contraseña de la clave. --cacert sobrescribe la lista de CAs confiables (por defecto: el almacén del sistema) — útil para CAs internas. mTLS es común en configuraciones zero-trust y service mesh.
# client certificate + private key (mTLS)
curl --cert client.pem --key client.key \
https://mtls.example.com/api
# PKCS#12 bundle (combined cert + key)
curl --cert client.p12 --cert-type P12 \
https://mtls.example.com/api
# password-protected key
curl --cert client.pem --key client.key \
--pass secret https://mtls.example.com/api
# PEM cert with password
curl --cert client.pem:secret https://mtls.example.com/api
# specify CA bundle to verify the server
curl --cacert custom-ca.pem https://internal.example.com
# mutual TLS with custom CA
curl --cert client.pem --key client.key \
--cacert internal-ca.pem \
https://mtls.internal.example.comVersión TLS
--tlsv1.X fija la versión mínima; --tls-max la limita. Forzar 1.2+ desactiva los protocolos heredados (SSLv3, TLS 1.0/1.1) con debilidades conocidas. Por defecto se negocia la versión más alta soportada mutuamente. -v revela la versión negociada y el cifrado en la línea 'SSL connection using'.
# force a minimum TLS version
curl --tlsv1.2 https://example.com
curl --tlsv1.3 https://example.com
# force an exact TLS version
curl --tls-max 1.2 https://example.com # cap at 1.2
curl --tls-max 1.3 https://example.com
# negotiate the highest version both support (default)
curl https://example.com
# disable specific versions
curl --tlsv1.2 --tls-max 1.2 https://example.com # only 1.2
# list versions curl supports
curl --version | grep -i tls
# debug which version was negotiated
curl -v https://example.com 2>&1 | grep -i "SSL connection"Cifrados y paquete de CAs
--ciphers restringe el conjunto de cifrados (sintaxis OpenSSL). --cacert apunta a un paquete de CAs personalizado para verificar servidores con CAs internas/privadas — por defecto se usa el paquete del sistema (/etc/ssl/certs o el keychain de macOS). Si el paquete de CAs está desactualizado, servidores con certificados válidos pueden ser rechazados; actualizar curl (o el paquete ca-certificates) lo corrige.
# specify allowed ciphers
curl --ciphers "AES256-GCM-SHA384:AES128-GCM-SHA256" \
https://example.com
# use a custom CA bundle to verify the server
curl --cacert /etc/ssl/certs/internal-ca.pem \
https://internal.example.com
# use the system CA store (default)
curl https://example.com
# use Mozilla's CA bundle (download separately)
curl --cacert cacert.pem https://example.com
# show the cipher used
curl -v https://example.com 2>&1 | grep -i cipher
# disable certificate revocation checks (CRL/OCSP)
curl --cacert ca.pem --no-clobber https://example.comInspección de certificados
Usa -v para inspeccionar el certificado del servidor (sujeto, emisor, fechas de validez). --pinnedpubkey aplica el certificate pinning — la petición falla si la clave pública del servidor no coincide, neutralizando CAs fraudulentas. Para depuración profunda de TLS, --trace-ascii vuelca el handshake completo. openssl s_client es una alternativa más potente para inspeccionar certificados.
# show the server certificate in verbose mode
curl -v https://example.com 2>&1 | grep -A1 "server certificate"
# extract certificate details (subject, issuer, dates)
curl -v https://example.com 2>&1 | grep -E "subject|issuer|start date|expire date"
# download the server certificate (PEM)
curl -v https://example.com 2>&1 | \
awk '/-----BEGIN CERT/,/-----END CERT/' > server.pem
# verify cert only, don't transfer body
curl -I https://example.com
# pin a specific certificate (fingerprint)
curl --pinnedpubkey sha256//BASE64= https://example.com
# check OCSP stapling
curl -v https://example.com 2>&1 | grep -i ocsp
# show full TLS trace
curl --trace-ascii - https://example.com | grep -i certDescargas
Guardar en archivo (-o/-O)
-o escribe en un nombre de archivo elegido; -O usa el nombre del archivo remoto (del basename de la URL). --output-dir fija la carpeta de destino para -O. Varios flags -O descargan varios archivos en una sola invocación. -o /dev/null descarta el body — útil para disparar webhooks o medir tiempos sin guardar datos.
# save with a custom name
curl -o page.html https://example.com/index.html
# save with the remote filename
curl -O https://example.com/file.zip
# save to a specific directory
curl -O --output-dir /tmp/downloads https://example.com/file.zip
# save with remote name to a specific dir
curl -o /tmp/file.zip https://example.com/file.zip
# download multiple files with remote names
curl -O https://example.com/a.zip -O https://example.com/b.zip
# save to /dev/null (just trigger the request)
curl -o /dev/null https://example.com/webhookReanudar descargas (-C)
-C - (--continue-at -) reanuda una descarga desde donde quedó, usando el tamaño existente del archivo como offset en bytes. El servidor debe soportar peticiones Range (comprueba Accept-Ranges: bytes). Combínalo con --retry para manejar conexiones inestables — curl reintenta y reanuda, evitando desperdiciar ancho de banda.
# resume a partial download
curl -C - -o file.zip https://example.com/file.zip
curl --continue-at - -o file.zip https://example.com/file.zip
# resume with -O (remote name)
curl -C - -O https://example.com/file.zip
# start download at a specific byte offset
curl -C 1024 -o file.zip https://example.com/file.zip
# server must support Range requests
curl -I https://example.com/file.zip | grep -i accept-ranges
# resume an interrupted large download
curl -C - --progress-bar -O https://example.com/bigfile.iso
# combine with retry for unreliable connections
curl -C - --retry 5 --retry-all-errors -O \
https://example.com/bigfile.isoBarra de progreso
--progress-bar muestra una barra ### más simple en lugar del medidor por defecto. -s silencia el progreso por completo; -sS conserva los errores. El progreso va a stderr, así que no contamina el body en stdout — puedes capturar ambos por separado. -w con %{size_download} y %{time_total} da un resumen limpio de una línea para scripts.
# default progress meter
curl -O https://example.com/file.zip
# simple progress bar (alternative style)
curl --progress-bar -O https://example.com/file.zip
# silent (no progress, no body output)
curl -s -O https://example.com/file.zip
# silent but still show errors
curl -sS -O https://example.com/file.zip
# show only errors (no progress, body to file)
curl -sS -o file.zip https://example.com/file.zip
# custom one-line progress
curl -o file.zip -w "%{size_download} bytes in %{time_total}s\n" \
https://example.com/file.zip
# redirect progress to a file, body to another
curl -o file.zip --progress-bar 2> progress.log \
https://example.com/file.zipRango de descarga
-r (--range) solicita un rango de bytes, devolviendo 206 Partial Content. Útil para previsualizar archivos grandes, reanudar o descargas paralelas multiconexión. El servidor debe anunciar Accept-Ranges: bytes. Combínalo con el segundo plano del shell (&) para descargar rangos concurrentemente y luego concatenar — la base de aceleradores de descarga como aria2.
# download bytes 0-1023 (first 1KB)
curl -r 0-1023 -o part1.bin https://example.com/file.zip
# download from byte 1024 to end
curl -r 1024- -o rest.bin https://example.com/file.zip
# download last 500 bytes
curl -r -500 -o tail.bin https://example.com/file.zip
# check if server supports ranges
curl -I https://example.com/file.zip | grep -i accept-ranges
# Accept-Ranges: bytes -> supported
# parallel range download (split a large file)
curl -r 0-49999999 -o part1.bin https://example.com/big.iso &
curl -r 50000000-99999999 -o part2.bin https://example.com/big.iso &
wait
cat part1.bin part2.bin > big.iso
# HTTP/1.1 206 Partial Content confirms success
curl -r 0-100 -v https://example.com/file.zip 2>&1 | grep HTTPMúltiples archivos y globbing
El globbing de URL ([1-3], {a,b,c}) emite una petición por expansión. --output-dir fija dónde los guarda -O. Para paralelismo real (curl por sí solo es secuencial), pasa las URLs a xargs -P N para ejecutar N curls a la vez. Esto acelera drásticamente la descarga de muchos archivos pequeños del mismo host (respeta los límites de tasa del servidor).
# download file1.zip, file2.zip, file3.zip
curl -O https://example.com/file[1-3].zip
# download with a step (1, 3, 5, 7, 9)
curl -O https://example.com/file[1-9:2].zip
# download from multiple paths
curl -O https://example.com/{a,b,c}.zip
# download to a specific directory
curl -O --output-dir /tmp/downloads \
https://example.com/file[1-3].zip
# sequential download (one at a time)
for url in https://example.com/{a,b,c}.zip; do
curl -O "$url"
done
# parallel download with xargs
echo "https://example.com/{a,b,c}.zip" | tr ' ' '\n' | \
xargs -n1 -P3 curl -OEspejo y recursión
curl es de URL única por diseño — no recursa. Para espejar un sitio, usa wget --mirror o scripta la extracción de enlaces con grep. Para descargas en lote, lista las URLs en un archivo y aliméntalo a xargs -P N para paralelismo. El ejemplo del sitemap descarga todas las páginas indexadas por un sitio — práctico para instantáneas offline.
# curl doesn't recurse like wget, but you can script it
# download a page and extract its links
curl -s https://example.com/ | \
grep -oP 'href="\K[^"]+' | grep '^http' > urls.txt
# download all linked PDFs
curl -s https://example.com/docs | \
grep -oP 'href="\K[^"]+\.pdf' | \
while read pdf; do curl -O "https://example.com/$pdf"; done
# use wget instead for true mirroring
# wget --mirror --convert-links --page-requisites https://example.com/
# download a list of URLs from a file
xargs -n1 -P4 curl -O < urls.txt
# fetch a sitemap and download every URL
curl -s https://example.com/sitemap.xml | \
grep -oP '<loc>\K[^<]+' | xargs -n1 -P4 curl -OTimeouts y reintentos
Timeout de conexión
--connect-timeout limita el tiempo para establecer la conexión TCP/TLS (pero no la transferencia). Sin él, curl puede colgarse minutos con hosts inalcanzables (por defecto del SO ~2 minutos). Fija siempre tanto --connect-timeout (fallar rápido con hosts muertos) como --max-time (limitar toda la operación) en scripts para evitar cuelgues.
# max time to establish the connection (seconds)
curl --connect-timeout 10 https://example.com
# connect timeout in milliseconds (curl 7.32+)
curl --connect-timeout 2.5 https://example.com
# connect timeout + overall max time
curl --connect-timeout 10 --max-time 30 https://example.com
# DNS resolution timeout (curl 7.88+, otherwise OS-controlled)
curl --happy-eyeballs-timeout-ms 1000 https://example.com
# fail fast on unreachable hosts
curl --connect-timeout 3 -sS https://example.com || echo "unreachable"
# combine with --retry for resilience
curl --connect-timeout 5 --max-time 20 --retry 3 \
https://example.comTiempo máximo
--max-time (-m) limita toda la operación (DNS + conexión + transferencia). --speed-time/--speed-limit abortan si la transferencia cae por debajo de una tasa de bytes durante un tiempo — perfecto para descargas estancadas. El código de salida 28 significa timeout; comprueba $? en scripts. Fija siempre un max-time para evitar cuelgues infinitos con servidores lentos o atascados.
# overall timeout for the whole operation
curl --max-time 30 https://example.com
curl -m 30 https://example.com
# max time in milliseconds (decimal)
curl --max-time 2.5 https://example.com
# max time with no data transfer (idle timeout)
curl --speed-time 30 --speed-limit 1000 https://example.com
# abort if speed < 1000 bytes/sec for 30 sec
# max time for a file upload
curl -T big.iso --max-time 600 https://example.com/upload
# max time per redirect hop
curl -L --max-time 60 https://example.com/redirect
# check exit code (28 = timed out)
curl --max-time 5 https://slow.example.com || echo "exit code: $?"Reintentos
--retry reintenta ante errores transitorios (timeouts, 5xx, 429) por defecto; --retry-all-errors lo extiende a cualquier fallo. --retry-delay añade una espera fija (duplicada en cada intento) entre reintentos. --retry-connrefused reintenta incluso cuando se rechaza la conexión (por ejemplo, servidor reiniciándose). Emparéjalo con -C - para reanudar descargas parciales. Es esencial para scripts resilientes.
# retry up to 3 times on transient errors
curl --retry 3 https://example.com
# retry on any error (not just transient)
curl --retry 3 --retry-all-errors https://example.com
# retry with exponential backoff
curl --retry 5 --retry-delay 2 https://example.com
# waits 2s, 4s, 6s, 8s, 10s between retries (curl 7.66+)
# retry on connection-refused specifically
curl --retry 3 --retry-connrefused https://example.com
# retry only on HTTP 5xx and 429
curl --retry 3 --retry-all-errors \
-H "Accept: application/json" https://api.example.com
# combine with resume for large downloads
curl --retry 5 --retry-all-errors -C - -O \
https://example.com/bigfile.isoRetardo de reintento y backoff
--retry-delay N espera N segundos antes del primer reintento y luego duplica (N, 2N, 4N...). curl respeta el header Retry-After del servidor para respuestas 429/503. Para lógica personalizada (jitter, espera máxima total, condición según código de estado), envuelve curl en un bucle de shell. Emparéja siempre --retry con --max-time para que los reintentos no duren para siempre.
# fixed delay between retries
curl --retry 5 --retry-delay 2 https://example.com
# exponential backoff (curl doubles the delay each time)
curl --retry 5 --retry-delay 1 https://example.com
# waits: 1s, 2s, 4s, 8s, 16s
# honor Retry-After header (default with --retry)
curl --retry 3 https://example.com
# cap retry delay with a max-time
curl --retry 10 --retry-delay 1 --max-time 60 https://example.com
# custom backoff in a shell loop
for i in 1 2 3 4 5; do
curl -s --max-time 10 https://example.com && break
echo "attempt $i failed, waiting $((i*2))s..."
sleep $((i*2))
done
# retry on specific HTTP status codes
curl --retry 5 --retry-all-errors \
-w "%{http_code}" -o /dev/null -s https://example.comLímites de velocidad
--speed-time/--speed-limit aborta una transferencia estancada (sin datos durante N segundos a una tasa por debajo del límite) — código de salida 28. --limit-rate limita la tasa de transferencia (soporta sufijos K/M/G), útil para no saturar el ancho de banda o para probar redes lentas. Combínalo con --retry para reanudar automáticamente descargas estancadas.
# abort if speed drops below 1000 bytes/sec for 30 sec
curl --speed-limit 1000 --speed-time 30 -O \
https://example.com/bigfile.iso
# shorthand: --speed-time defaults to 30 if only --speed-limit is set
curl --speed-limit 1000 -O https://example.com/bigfile.iso
# limit max download rate (bytes/sec)
curl --limit-rate 100k -O https://example.com/file.zip
# limit rate with units (K, M, G)
curl --limit-rate 1M -O https://example.com/file.zip
# limit upload rate
curl -T big.iso --limit-rate 500k https://example.com/upload
# combine with retry on stall
curl --speed-limit 1000 --speed-time 30 \
--retry 5 --retry-all-errors \
-O https://example.com/bigfile.isoDepuración
Verboso (-v)
-v (verbose) es la herramienta de depuración principal. Las líneas '>' son la petición, las '<' son la respuesta, las '*' son internos de curl (DNS, TLS, conexión) — eso va a stderr, así que stdout queda limpio para el body. Redirige 2>&1 para filtrar con grep. Usa -o /dev/null para inspeccionar los headers sin guardar el body.
# verbose: full request + response + curl internals
curl -v https://example.com
# output goes to stderr; body to stdout
curl -v https://example.com > body.txt 2> debug.log
# only show request headers (> lines)
curl -v https://example.com 2>&1 | grep '^>'
# only show response headers (< lines)
curl -v https://example.com 2>&1 | grep '^<'
# only show curl info (* lines)
curl -v https://example.com 2>&1 | grep '^\*'
# verbose without sending the body
curl -v -o /dev/null https://example.comTrace
--trace vuelca la conversación completa (incluido el body) en hex + ASCII; --trace-ascii se salta el hex. --trace-time añade marcas de tiempo. A diferencia de -v, trace muestra los bodies de petición y respuesta, así que es la herramienta de referencia para depurar datos binarios o comprimidos. Advertencia: --trace registra secretos (contraseñas, tokens) — limpiados antes de compartir.
# trace: dump all sent and received data (hex + ASCII)
curl --trace - https://example.com
# trace ASCII only (no hex dump)
curl --trace-ascii - https://example.com
# trace to a file
curl --trace trace.log https://example.com
# trace including time per packet
curl --trace-ascii - --trace-time https://example.com
# trace with request body (hidden by default in -v)
curl --trace-ascii - -d "secret=data" https://example.com
# compare verbose vs trace
curl -v https://example.com 2>&1 | head
curl --trace-ascii - https://example.com | headSolo headers
-I envía una petición HEAD (la mayoría de servidores devuelven los mismos headers que GET sin el body). -D vuelca los headers a un archivo o a '-' (stdout). Para ver lo que curl envió (headers de petición), usa -v y grep '^>'. Para solo el código de estado, -w '%{http_code}' es lo más limpio. Ojo: algunos servidores responden distinto a HEAD que a GET.
# HEAD request: response headers only
curl -I https://example.com
curl --head https://example.com
# dump response headers to stdout, discard body
curl -D - -o /dev/null https://example.com
# dump response headers to a file
curl -D headers.txt -o body.html https://example.com
# show request headers (what curl sent)
curl -v -o /dev/null https://example.com 2>&1 | grep '^>'
# show both request and response headers
curl -v -o /dev/null https://example.com 2>&1 | grep -E '^[<>]'
# show only the status line
curl -s -o /dev/null -w "%{http_code} %{http_version}\n" \
https://example.com
curl -D - -o /dev/null -s https://example.com | head -1Separación de petición y respuesta
La salida verbosa va a stderr y el body a stdout, así que pueden capturarse por separado con redirección. -D guarda los headers de respuesta; -o guarda el body; -v (stderr) captura la conversación completa. Esta separación es esencial para depurar APIs: inspecciona headers y body de forma independiente, registra tiempos y compara petición vs respuesta.
# capture request and response separately
curl -v https://example.com \
-o body.txt \
1> /dev/null 2> verbose.log
# extract request only
curl -v https://example.com 2>&1 1>/dev/null | grep '^>' > request.txt
# extract response only
curl -v https://example.com 2>&1 1>/dev/null | grep '^<' > response.txt
# split headers and body cleanly
curl -s -D headers.txt -o body.txt https://example.com
# capture everything: body, headers, request, timing
curl -s -D headers.txt -o body.txt \
-w "@curl-format.txt" https://example.com >> timing.log
# show body to terminal, headers to file
curl -D headers.txt https://example.comOpciones de depuración
--dry-run imprime lo que curl haría sin enviar — genial para verificar el globbing de URL y la configuración. --resolve fija un host a una IP, saltándose el DNS (esencial para probar un backend concreto). --interface se enlaza a una tarjeta de red o IP. --no-keepalive fuerza una conexión nueva por petición, útil para reproducir bugs a nivel de conexión.
# show what curl would do without sending
curl --dry-run https://example.com
# dump parsed config files
curl --config /dev/null -v https://example.com 2>&1 | grep -i config
# force a fresh connection (no keep-alive reuse)
curl --no-keepalive https://example.com
# disable DNS cache
curl --doh-url https://dns.example.com/dns-query https://example.com
# use a specific network interface
curl --interface eth0 https://example.com
curl --interface 192.168.1.5 https://example.com
# resolve a hostname to a specific IP (no DNS)
curl --resolve example.com:443:1.2.3.4 https://example.com
# debug globbing (list URLs without fetching)
curl --dry-run -O https://example.com/file[1-3].zipInformación de la respuesta
Código de estado HTTP
-w '%{http_code}' extrae solo el código de estado para scripting. -f (--fail) hace que curl salga con error en 4xx/5xx (sin él, curl devuelve 0 incluso para 404). --fail-with-body también imprime el body de la respuesta en caso de error (más útil para depurar). Usa el código de estado para ramificar en scripts: 2xx éxito, 3xx redirección, 4xx error del cliente, 5xx error del servidor.
# get only the status code
curl -s -o /dev/null -w "%{http_code}" https://example.com
echo # 200
# status code with newline
curl -s -o /dev/null -w "%{http_code}\n" https://example.com
# full status line
curl -s -o /dev/null -w "%{http_version} %{http_code}\n" https://example.com
# branch on status code
CODE=$(curl -s -o /dev/null -w "%{http_code}" https://example.com)
if [ "$CODE" = "200" ]; then echo "ok"; else echo "fail: $CODE"; fi
# fail on HTTP errors (4xx, 5xx)
curl -f https://example.com || echo "HTTP error"
curl --fail-with-body https://example.com # 7.76+: still print body
# check redirect chain status codes
curl -L -w "%{num_redirects} redirects, final %{http_code}\n" \
-o /dev/null -s https://short.url/abcFormato write-out
-w (--write-out) formatea información sobre la transferencia usando placeholders %{variable}. Los tiempos (time_namelookup, time_connect, time_appconnect, time_total) descomponen dónde se gasta el tiempo — esencial para análisis de rendimiento. %{json} muestra todas las variables como JSON (curl 7.70+). Guarda un formato en un archivo y usa -w @file para reutilizarlo.
# built-in variables with -w / --write-out
curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" \
https://example.com
# URL info
curl -s -o /dev/null -w "URL: %{url_effective}\nIP: %{remote_ip}\n" \
https://example.com
# timing breakdown
curl -s -o /dev/null \
-w "dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} total=%{time_total}\n" \
https://example.com
# size info
curl -s -o /dev/null \
-w "downloaded=%{size_download} uploaded=%{size_upload}\n" \
https://example.com
# write format from a file
cat > fmt.txt <<EOF
http_code: %{http_code}
time_total: %{time_total}s
EOF
curl -s -o /dev/null -w "@fmt.txt" https://example.com
# JSON output (curl 7.70+)
curl -s -o /dev/null -w "%{json}" https://example.comTiempo de respuesta
Las variables de tiempo descomponen la petición: time_namelookup (DNS), time_connect (TCP), time_appconnect (TLS), time_starttransfer (TTFB — primer byte recibido), time_total (toda la transferencia). TTFB es la métrica clave para la latencia de APIs. Compara tiempos entre endpoints para identificar cuellos de botella (DNS, red, TLS o procesamiento del servidor).
# total time
curl -s -o /dev/null -w "%{time_total}\n" https://example.com
# DNS resolution time
curl -s -o /dev/null -w "%{time_namelookup}\n" https://example.com
# TCP connect time
curl -s -o /dev/null -w "%{time_connect}\n" https://example.com
# TLS handshake time (after connect)
curl -s -o /dev/null -w "%{time_appconnect}\n" https://example.com
# time to first byte (TTFB)
curl -s -o /dev/null -w "%{time_starttransfer}\n" https://example.com
# full timing breakdown
curl -s -o /dev/null -w \
"dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
https://example.com
# compare two endpoints
curl -s -o /dev/null -w "%{time_total}\n" https://api1.example.com
curl -s -o /dev/null -w "%{time_total}\n" https://api2.example.comExtraer headers
-D - vuelca los headers de respuesta a stdout; pásalo por pipe con grep para extraer un header concreto. -I (HEAD) también sirve pero puede diferir de GET. -w proporciona %{url_effective} (URL final tras redirecciones), %{remote_ip} (IP del servidor) y %{num_redirects}. Son inestimables para depurar el enrutado de CDN, redirecciones e identificación del servidor.
# dump all response headers to stdout, discard body
curl -s -D - -o /dev/null https://example.com
# extract one header (Content-Type)
curl -s -D - -o /dev/null https://example.com | \
grep -i "^content-type:"
# extract Content-Length (size)
curl -s -I https://example.com/file.zip | grep -i content-length
# extract Set-Cookie
curl -s -D - -o /dev/null https://example.com | grep -i set-cookie
# extract the final URL after redirects
curl -s -L -o /dev/null -w "%{url_effective}\n" https://short.url/abc
# extract the server's IP address
curl -s -o /dev/null -w "%{remote_ip}\n" https://example.com
# count redirects
curl -s -L -o /dev/null -w "%{num_redirects}\n" https://short.url/abcVariables de formato
-w (--write-out) soporta decenas de variables (ejecuta 'curl -w "%{json}"' para verlas en conjunto como JSON). Las variables de tiempo son la base del monitoreo de rendimiento; las de tamaño siguen el ancho de banda; url_effective y num_redirects depuran el enrutado. %{json} (curl 7.70+) es la forma más fácil de capturar el conjunto completo para logs o dashboards.
# complete list of common -w variables
# %{http_code} - response status code
# %{http_version} - HTTP version (1.1, 2, 3)
# %{url_effective} - final URL after redirects
# %{remote_ip} - server IP address
# %{remote_port} - server port
# %{time_namelookup} - DNS resolution time
# %{time_connect} - TCP connect time
# %{time_appconnect} - TLS handshake time
# %{time_pretransfer} - time before transfer starts
# %{time_starttransfer} - TTFB (first byte)
# %{time_total} - total time
# %{size_download} - bytes downloaded
# %{size_upload} - bytes uploaded
# %{size_header} - header bytes
# %{size_request} - request bytes
# %{num_redirects} - number of redirects
# %{ssl_verify_result}- SSL verification result
# %{content_type} - response content type
# %{json} - all variables as JSON (7.70+)
# reference: curl -w "%{json}" https://example.com
curl -s -o /dev/null -w "%{json}" https://example.com | jqFTP y SMTP
Fundamentos de FTP
curl soporta FTP tanto para descargas (GET) como para subidas (PUT vía -T). -u proporciona credenciales; el FTP anónimo usa 'anonymous' + un correo. FTPS (--ftp-ssl) cifra el canal de control. El modo pasivo (por defecto) funciona a través de NAT/firewalls; usa --ftp-port para el modo activo si el servidor lo exige.
# anonymous FTP download
curl ftp://ftp.example.com/file.txt
# authenticated FTP
curl -u user:pass ftp://ftp.example.com/file.txt
# list a directory
curl ftp://ftp.example.com/directory/
# download a file
curl -O ftp://ftp.example.com/file.txt
# upload a file (PUT)
curl -T local.txt ftp://ftp.example.com/remote.txt -u user:pass
# use explicit FTPS (FTP over TLS)
curl --ftp-ssl ftp://ftp.example.com/file.txt -u user:pass
# passive mode (default; needed behind NAT/firewalls)
curl --ftp-pasv ftp://ftp.example.com/ -u user:passSubida FTP
-T sube un archivo vía el comando STOR de FTP. --ftp-create-dirs crea los directorios padre con MKD. --append usa APPE para añadir a un archivo existente. -C - reanuda una subida interrumpida. El globbing ({a,b}) sube varios archivos en una sola invocación. Para directorios, taréalos primero — FTP no puede subir carpetas directamente.
# upload a single file
curl -T local.txt ftp://ftp.example.com/remote.txt -u user:pass
# upload with explicit filename
curl -T local.txt -o remote.txt ftp://ftp.example.com/ -u user:pass
# upload to a directory
curl -T local.txt ftp://ftp.example.com/uploads/ -u user:pass
# create a directory (MKD command)
curl --ftp-create-dirs -T local.txt \
ftp://ftp.example.com/newdir/file.txt -u user:pass
# append to a remote file
curl -T local.txt --append ftp://ftp.example.com/remote.txt -u user:pass
# upload multiple files with globbing
curl -T "{file1,file2}.txt" ftp://ftp.example.com/ -u user:pass
# resume an interrupted upload
curl -C - -T bigfile.iso ftp://ftp.example.com/bigfile.iso -u user:passListado FTP
Una URL FTP terminada en / lista el directorio. --list-only devuelve solo los nombres de archivo. -v muestra los comandos FTP subyacentes (USER, PASS, PASV, LIST, RETR) — inestimable para depurar problemas de permisos o firewall. curl no puede recursar en subdirectorios; usa wget --mirror o un script para descargas FTP recursivas.
# list a directory (default format)
curl ftp://ftp.example.com/ -u user:pass
# list with --list-only (names only, no details)
curl --list-only ftp://ftp.example.com/ -u user:pass
# list a specific directory
curl ftp://ftp.example.com/pub/ -u user:pass
# recursive listing (curl doesn't recurse natively)
# use --ftp-method to control PASV/EPSV behavior
curl --ftp-method nocwd ftp://ftp.example.com/ -u user:pass
# download all files in a directory (with globbing)
curl -O ftp://ftp.example.com/pub/*.txt -u user:pass
# show server responses (FTP commands)
curl -v ftp://ftp.example.com/ -u user:pass 2>&1 | grep -E "^\*|^[<>]"Enviar correo SMTP
curl puede enviar correo vía SMTP. El body (con headers) va en un archivo pasado por pipe vía -T. --mail-from y --mail-rcpt fijan el sobre (separado de los headers To/From del body). --ssl-reqd fuerza STARTTLS (puerto 587); smtps:// usa TLS implícito (puerto 465). Autenticación vía -u (LOGIN/PLAIN). Genial para alertas scriptadas desde servidores sin cliente de correo.
# send email via SMTP
curl --url "smtp://smtp.example.com:587" \
--mail-from "[email protected]" \
--mail-rcpt "[email protected]" \
-u "[email protected]:password" \
-T email.txt
# email body from a file
cat > email.txt <<EOF
From: [email protected]
To: [email protected]
Subject: Test from curl
Hello from curl!
EOF
curl --url "smtp://smtp.example.com:587" \
--mail-from "[email protected]" \
--mail-rcpt "[email protected]" \
-u "[email protected]:password" \
--ssl-reqd \
-T email.txt
# multiple recipients
curl --url "smtp://smtp.example.com:587" \
--mail-from "[email protected]" \
--mail-rcpt "[email protected]" \
--mail-rcpt "[email protected]" \
-T email.txt
# STARTTLS (port 587)
curl --ssl-reqd --url "smtp://smtp.example.com:587" \
--mail-from "[email protected]" --mail-rcpt "[email protected]" \
-T email.txt
# SMTPS (implicit TLS, port 465)
curl --url "smtps://smtp.example.com:465" \
--mail-from "[email protected]" --mail-rcpt "[email protected]" \
-T email.txtIMAP y POP3
curl puede leer correo vía IMAP y POP3. La sintaxis de URL incluye selectores de carpeta, UID y sección. IMAP soporta búsqueda (?UNSEEN, ?SUBJECT, etc.). imaps:// y pop3s:// usan TLS implícito. Ojo: curl es de solo lectura para correo — puede obtener pero no enviar vía IMAP/POP3 (usa SMTP para enviar). El body se devuelve como texto crudo del mensaje RFC 822.
# list IMAP mailboxes
curl -u "user:pass" --url "imap://imap.example.com:143"
# list messages in INBOX
curl -u "user:pass" --url "imap://imap.example.com/INBOX"
# fetch a specific message (UID 1)
curl -u "user:pass" --url "imap://imap.example.com/INBOX;UID=1"
# fetch message headers only
curl -u "user:pass" --url "imap://imap.example.com/INBOX;UID=1;SECTION=HEADER"
# search for unread messages
curl -u "user:pass" --url "imap://imap.example.com/INBOX?UNSEEN"
# POP3: list messages
curl -u "user:pass" --url "pop3://pop.example.com/"
# POP3: retrieve message #1
curl -u "user:pass" --url "pop3://pop.example.com/1"
# use IMAPS (implicit TLS, port 993)
curl -u "user:pass" --url "imaps://imap.example.com/INBOX"FTPS y SFTP
FTP tiene tres variantes cifradas: FTPS explícito (--ftp-ssl, se actualiza en el puerto 21), FTPS implícito (ftps://, TLS desde el inicio en el puerto 990) y SFTP (sftp://, un protocolo completamente distinto sobre SSH en el puerto 22). SFTP soporta autenticación por clave vía --key (con --pass para claves cifradas). SFTP se prefiere hoy en general sobre FTPS por su simplicidad y su amabilidad con los firewalls.
# FTPS: explicit TLS (upgrade to TLS on plain FTP port)
curl --ftp-ssl --ssl-reqd ftp://ftp.example.com/ -u user:pass
# FTPS: implicit TLS (TLS from the start, port 990)
curl ftps://ftp.example.com:990/ -u user:pass
# SFTP (SSH File Transfer Protocol, port 22)
curl -u user sftp://sftp.example.com/file.txt
# SFTP with key authentication
curl -u user --key ~/.ssh/id_rsa \
sftp://sftp.example.com/file.txt
# SFTP with a password-protected key
curl -u user --key ~/.ssh/id_rsa --pass passphrase \
sftp://sftp.example.com/file.txt
# SFTP upload
curl -u user -T local.txt sftp://sftp.example.com/remote.txt
# SFTP list directory
curl -u user sftp://sftp.example.com/Paralelo y lote
Descargas paralelas
curl por sí solo es secuencial — para descargar concurrentemente, ejecuta varios curls en paralelo con & y wait, o usa xargs -P N para correr N a la vez. Esto acelera drásticamente muchos archivos pequeños. Sé considerado: demasiadas conexiones paralelas pueden saturar al servidor o provocarte un rate limit. 4-8 concurrentes es un valor por defecto razonable.
# background multiple curls (shell parallelism)
curl -O https://example.com/a.zip &
curl -O https://example.com/b.zip &
curl -O https://example.com/c.zip &
wait
# parallel with xargs (4 concurrent)
echo -e "https://example.com/a.zip\nhttps://example.com/b.zip" | \
xargs -n1 -P4 curl -O
# parallel with a URL list file
xargs -n1 -P4 curl -O < urls.txt
# zsh-specific parallel with {..}
for url in https://example.com/{a,b,c}.zip; do
curl -O "$url" &
done; wait
# bash-specific using arrays and &
urls=("https://example.com/a.zip" "https://example.com/b.zip")
for url in "${urls[@]}"; do curl -O "$url" & done; waitParalelo con xargs
xargs -P N ejecuta N procesos concurrentemente, alimentando cada línea de stdin como argumento. -a lee de un archivo. -I {} te permite colocar la URL en cualquier parte del comando. Es la forma más simple de paralelizar descargas con curl sin herramientas extra. Para limitación consciente del host o lógica de reintento compleja, usa un gestor de descargas dedicado como aria2c.
# download each URL from a file, 4 concurrent
xargs -n1 -P4 -a urls.txt curl -O
# download with custom names, parallel
cat urls.txt | xargs -n2 -P4 sh -c 'curl -o "$0" "$1"'
# download and process each response
cat urls.txt | xargs -n1 -P4 -I {} sh -c \
'curl -s {} | jq .field'
# retry failures in parallel
xargs -n1 -P4 -a urls.txt curl --retry 3 -O
# limit total concurrent connections to a host
# (xargs doesn't know about hosts; use a queue or a download manager)
xargs -n1 -P4 -a urls.txt curl -O --limit-rate 1M
# show progress for parallel downloads
xargs -n1 -P4 -a urls.txt curl -O --progress-bar 2>&1Globbing de URL
El globbing expande las URLs en múltiples peticiones: rangos [1-10] (con :step opcional y relleno de ceros con ceros iniciales) y listas {a,b,c}. -o 'file#1.zip' usa #1 como contador para nombres de salida personalizados. -g (--globoff) desactiva la expansión — esencial para URLs que contienen [ ] o { } literales (JSON, IPv6).
# numeric range: 1, 2, 3
curl -O https://example.com/file[1-3].zip
# range with step: 0, 5, 10, 15, 20
curl -O https://example.com/file[0-20:5].zip
# leading zeros (zero-padded)
curl -O https://example.com/file[01-10].zip # 01, 02, ..., 10
# list expansion: a, b, c
curl -O https://example.com/{a,b,c}.zip
# nested globs
curl -O https://example.com/{v1,v2}/file[1-2].txt
# save each with a custom name pattern
curl -o "file#1.zip" https://example.com/file[1-3].zip
# disable globbing (literal brackets)
curl -g "https://example.com/file[1].zip"Rango secuencial
Para descargas secuenciales (cuando el paralelismo saturaría al servidor o violaría los límites de tasa), itera sobre las URLs en bash. Añade sleep por cortesía. -sf (silent + fail) hace que curl salga con error en errores HTTP para que el bucle pueda cortar temprano. Este es el patrón seguro para scraping o crawling: sé respetuoso, añade retardos y maneja los errores.
# fetch URLs one at a time (no parallelism)
for i in 1 2 3 4 5; do
curl -O "https://example.com/page$i.html"
done
# range with brace expansion (bash/zsh)
for i in {1..10}; do
curl -s -O "https://example.com/page$i.html"
done
# with a delay between requests (rate limiting)
for i in {1..10}; do
curl -s -O "https://example.com/page$i.html"
sleep 1
done
# retry each URL individually
for url in $(cat urls.txt); do
curl -s --retry 3 -O "$url"
done
# conditional: stop on first error
for url in $(cat urls.txt); do
curl -sf -O "$url" || { echo "failed: $url"; break; }
doneGNU parallel y curl
GNU parallel es más potente que xargs: conserva el orden de salida, muestra progreso (--bar) y maneja argumentos con más flexibilidad. -j N fija la concurrencia. :::: lee de un archivo, ::: de la línea de comandos. Parallel es ideal para pruebas de API en lote, scraping y benchmarks donde necesitas salida limpia y ordenada de peticiones concurrentes.
# GNU parallel: smarter than xargs (preserves order, progress)
parallel -j4 curl -O {} ::: https://example.com/a.zip \
https://example.com/b.zip
# parallel from a file
parallel -j4 curl -O :::: urls.txt
# parallel with progress bar
parallel --bar -j4 curl -O :::: urls.txt
# parallel with output capture
parallel -j4 'curl -s -o {}.out {}' :::: urls.txt
# parallel with retry and timing
parallel -j4 'curl -s -w "{} %{time_total}s\n" -o /dev/null {}' :::: urls.txt
# parallel POST requests
parallel -j4 'curl -s -X POST -d "id={}" https://api.example.com/{}' \
::: 1 2 3 4 5
# combine with --dry-run to preview
parallel --dry-run -j4 curl -O :::: urls.txtArchivos de configuración
Fundamentos de .curlrc
~/.curlrc guarda opciones por defecto aplicadas a cada invocación de curl. Usa nombres de opción largos sin el -- inicial. Una opción por línea; los valores pueden entrecomillarse. Esto mantiene ajustes comunes (timeouts, reintentos, User-Agent) consistentes entre scripts y uso interactivo. Sobrescríbelos por petición pasando la opción explícitamente en la línea de comandos.
# ~/.curlrc is read automatically by curl
# one option per line, long option names without the --
# ~/.curlrc example:
# show progress by default
silent
# always follow redirects
location
# default User-Agent
user-agent = "MyApp/1.0"
# default headers
header = "Accept: application/json"
# retry transient errors
retry = 3
# connect timeout
connect-timeout = 10
# max time
max-time = 30
# lines starting with # are comments
# blank lines are ignored
# test: curl https://example.com now uses all the aboveUbicación del archivo de configuración
curl lee ~/.curlrc (o $CURL_HOME/.curlrc) por defecto. -K (--config) apunta a un archivo específico; -K - lee de stdin. -q (--disable) se salta por completo el archivo de configuración — útil cuando una opción por defecto rompe una petición concreta. CURL_HOME reubica el directorio de búsqueda para configuraciones portátiles.
# default locations (searched in order):
# 1. ~/.curlrc (or $CURL_HOME/.curlrc)
# 2. /etc/curl/curlrc (system-wide, if compiled in)
# set a custom config directory
export CURL_HOME=/etc/curl
# curl then reads $CURL_HOME/.curlrc
# specify a config file explicitly
curl -K /path/to/myconfig https://example.com
curl --config /path/to/myconfig https://example.com
# read config from stdin
echo "silent" | curl -K - https://example.com
# disable config file reading
curl -q https://example.com
curl --disable https://example.com
# check which config curl reads
curl -v https://example.com 2>&1 | grep -i configConfiguración con -K
-K carga opciones de un archivo, perfecto para configuraciones por entorno (tokens de dev vs prod, timeouts, headers). Guardar secretos en un archivo de configuración (chmod 600) los mantiene fuera del historial del shell y de ps. Varios archivos -K se procesan en orden, así que los últimos sobrescriben a los primeros — útil para una configuración base más anulaciones específicas por entorno.
# use a config file for a specific request
curl -K prod.conf https://api.example.com/data
# prod.conf:
# header = "Authorization: Bearer prod-token"
# header = "X-Environment: production"
# connect-timeout = 5
# max-time = 20
# dev.conf (different settings)
# header = "Authorization: Bearer dev-token"
# header = "X-Environment: development"
# max-time = 60
# switch environments by config file
curl -K dev.conf https://api.example.com/data
curl -K prod.conf https://api.example.com/data
# config file with URL
# echo "url = https://api.example.com/data" > req.conf
curl -K req.conf
# multiple config files (later ones override earlier)
curl -K defaults.conf -K override.conf https://example.comValores por defecto comunes
Un ~/.curlrc sólido hace que cada invocación de curl sea más segura y consistente: los timeouts evitan cuelgues, los reintentos manejan fallos transitorios, --compressed maneja gzip de forma transparente, y un User-Agent recortado reduce el fingerprinting. La línea write-out registra el tiempo y el estado de cada petición — inestimable para comprobaciones rápidas de rendimiento.
# ~/.curlrc with sensible production defaults
# always follow redirects
location
# limit redirects
max-redirs = 5
# timeouts (fail fast, cap total)
connect-timeout = 10
max-time = 60
# retry transient failures
retry = 3
retry-delay = 2
retry-all-errors
# show errors even when silent
show-error
# auto-decompress responses
compressed
# negotiate HTTP/2
http2
# verify SSL by default (explicit for clarity)
cacert = /etc/ssl/certs/ca-certificates.crt
# don't leak the curl version
user-agent = ""
# verbose timing on failure
write-out = "time: %{time_total}s code: %{http_code}\n"Múltiples configuraciones
Dividir la configuración en archivos por capas (base, auth, api, entorno) mantiene la configuración modular y segura. Procesalos con varios flags -K en orden — los últimos archivos sobrescriben a los primeros. Pon los secretos en un archivo con permisos 600 fuera del control de versiones. Un script envolvente que cargue la pila te permite llamar a 'mycurl' con los valores por defecto aplicados.
# base.conf — shared defaults
# silent
# show-error
# compressed
# connect-timeout = 10
# max-time = 30
# auth.conf — credentials (chmod 600)
# user = alice:secret
# header = "Authorization: Bearer TOKEN"
# api.conf — API-specific options
# header = "Accept: application/json"
# header = "X-Client: my-app/2.0"
# retry = 5
# combine configs in order (later overrides earlier)
curl -K base.conf -K auth.conf -K api.conf \
https://api.example.com/data
# config file referencing another (nesting not supported)
# but you can source them in a wrapper script:
# #!/bin/bash
# curl -K base.conf -K auth.conf -K api.conf "$@"
# environment-specific overlay
curl -K base.conf -K "${ENV}.conf" https://api.example.comTécnicas avanzadas
Reutilización de conexiones
Dentro de una sola invocación de curl, la conexión TCP se reutiliza entre varias URLs del mismo host (HTTP keep-alive), ahorrando la sobrecarga del handshake TLS. --no-keepalive lo desactiva. --max-connects limita las conexiones concurrentes en descargas multi-URL. Entre llamadas separadas de curl no hay reutilización de conexión — para eso, usa un cliente persistente como httpie o un script en Python/Node.
# curl reuses connections within a single invocation
# multiple URLs in one command share the TCP connection
curl -o a.txt https://example.com/a \
-o b.txt https://example.com/b
# keep-alive is on by default
# disable it for a single request
curl --no-keepalive https://example.com
# limit max connections (for multi-URL)
curl --max-connects 4 \
-O https://example.com/a -O https://example.com/b
# persistent session across shell calls (not natively supported)
# but you can use a config file to reduce overhead
curl -K session.conf https://example.com/a
curl -K session.conf https://example.com/b
# check if connection was reused
curl -v https://example.com 2>&1 | grep -i "Connection #0"HTTP/2 y HTTP/3
HTTP/2 multiplexa peticiones sobre una conexión; HTTP/3 usa QUIC sobre UDP, eliminando el bloqueo de cabeza de línea. --http2 negocia vía ALPN sobre TLS; --http2-prior-knowledge se salta la negociación (para h2c en claro). --http3 requiere una compilación especial de curl. Comprueba %{http_version} para confirmar qué se usó realmente. La mayoría de CDN modernas soportan h2 por defecto.
# negotiate HTTP/2 (needs TLS + ALPN)
curl --http2 https://example.com
# force HTTP/2 (fail if not available)
curl --http2-only https://example.com
# negotiate HTTP/3 (QUIC, needs curl built with quiche/openssl-quic)
curl --http3 https://example.com
# force HTTP/3 only
curl --http3-only https://example.com
# check what version was negotiated
curl -s -o /dev/null -w "%{http_version}" https://example.com
echo # 2 or 3
# list supported HTTP versions
curl --version | grep -i -E "http2|http3"
# HTTP/2 with prior knowledge (no upgrade negotiation)
curl --http2-prior-knowledge http://example.comPeticiones condicionales
Las peticiones condicionales ahorran ancho de banda: el servidor devuelve 304 Not Modified (sin body) si el recurso no cambió. -z (--time-cond) fija If-Modified-Since a partir de una fecha o del mtime de un archivo local. Para caché basada en ETag, fija If-None-Match manualmente. If-Unmodified-Since habilita la concurrencia optimista — el PUT falla si alguien más modificó el recurso.
# fetch only if modified since a date
curl -z "Wed, 21 Oct 2025 07:28:00 GMT" \
-O https://example.com/data.json
curl --timecond "Wed, 21 Oct 2025 07:28:00 GMT" \
-O https://example.com/data.json
# fetch only if changed (use a local file's mtime)
curl -z local_copy.json -O https://example.com/data.json
# ETag-based conditional (If-None-Match)
curl -H 'If-None-Match: "abc123"' \
-o data.json https://example.com/data.json
# server returns 304 Not Modified if ETag matches
# If-Modified-Since header manually
curl -H "If-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT" \
https://example.com/data.json
# If-Unmodified-Since (for concurrency control)
curl -X PUT -H "If-Unmodified-Since: Wed, 21 Oct 2025 07:28:00 GMT" \
-d '{"x":1}' https://api.example.com/dataInterfaz y DNS
--interface se enlaza a una tarjeta de red o IP — útil en máquinas multi-homed. --resolve fija un host a una IP, saltándose el DNS, y es genial para probar backends detrás de un balanceador. --doh-url usa DNS-over-HTTPS (privacidad). -4/-6 fuerzan la familia IP. Happy Eyeballs (por defecto) prueba IPv4 e IPv6 para evitar los retrasos del agujero negro IPv6.
# bind to a specific network interface
curl --interface eth0 https://example.com
curl --interface 192.168.1.5 https://example.com
# pin a hostname to an IP (skip DNS)
curl --resolve example.com:443:1.2.3.4 https://example.com
# pin multiple hosts
curl --resolve example.com:443:1.2.3.4 \
--resolve api.example.com:443:1.2.3.5 \
https://example.com/
# use a custom DNS server (DoH)
curl --doh-url https://dns.google/dns-query https://example.com
curl --doh-url https://cloudflare-dns.com/dns-query https://example.com
# use a specific DNS resolver (plain DNS, curl 7.84+)
curl --dns-servers 8.8.8.8,1.1.1.1 https://example.com
# happy eyeballs: try IPv4 and IPv6 in parallel
curl --happy-eyeballs-timeout-ms 200 https://example.com
# force IPv4 or IPv6
curl -4 https://example.com
curl -6 https://example.comPeticiones de rango y parciales
Las peticiones de rango (-r) obtienen parte de un archivo, devolviendo 206 Partial Content. Casos de uso: previsualizar archivos grandes, descargas paralelas multiconexión (dividir en rangos, obtener concurrentemente, concatenar) y reanudar transferencias interrumpidas (-C -). El servidor debe anunciar Accept-Ranges: bytes. Es la base de aceleradores de descarga como aria2.
# request a byte range (first 1024 bytes)
curl -r 0-1023 -o part.bin https://example.com/file.zip
# request from byte 1024 to end
curl -r 1024- -o rest.bin https://example.com/file.zip
# request last 500 bytes
curl -r -500 -o tail.bin https://example.com/file.zip
# check if server supports ranges
curl -I https://example.com/file.zip | grep -i accept-ranges
# download in parallel chunks
curl -r 0-49999999 -o part1.bin https://example.com/big.iso &
curl -r 50000000- -o part2.bin https://example.com/big.iso &
wait
cat part1.bin part2.bin > big.iso
# resume a partial download
curl -C - -o file.zip https://example.com/file.zip
# HTTP 206 = Partial Content (range succeeded)
curl -r 0-100 -v https://example.com/file.zip 2>&1 | grep HTTPCódigos de salida
Los códigos de salida de curl distinguen modos de fallo: 6 (DNS), 7 (conexión), 22 (error HTTP, solo con -f), 28 (timeout), 35 (TLS), 60 (certificado). Úsalos para construir scripts robustos que reintenten apropiadamente (por ejemplo, reintentar con 28 pero fallar rápido con 6). --fail-with-body devuelve el body de la respuesta incluso en 4xx/5xx, haciendo la depuración de errores de API mucho más fácil que -f.
# common curl exit codes:
# 0 - success
# 1 - unsupported protocol
# 3 - malformed URL
# 6 - couldn't resolve host (DNS failure)
# 7 - failed to connect
# 22 - HTTP error (use with -f)
# 26 - couldn't read a file (e.g., -d @missing.txt)
# 28 - operation timeout
# 35 - SSL connect error
# 47 - too many redirects
# 52 - server didn't reply anything
# 55 - failed sending network data
# 56 - failed receiving network data
# 60 - certificate verification failed
# check exit code
curl -sf https://example.com || echo "failed: $?"
# branch on specific codes
curl --max-time 5 https://example.com
case $? in
0) echo "ok" ;;
6) echo "DNS failure" ;;
7) echo "connection refused" ;;
28) echo "timeout" ;;
*) echo "error: $?" ;;
esac
# treat HTTP errors as failures
curl -f https://api.example.com || echo "HTTP error"
# still print body on HTTP error (7.76+)
curl --fail-with-body https://api.example.comFragmentos de curl relacionados
Copy-paste ready code for common tasks.
HTTP Methods
GET, POST, PUT, and DELETE requests.
Headers
Set and inspect request and response headers.
Authentication
Basic, bearer, and OAuth credentials.
Cookies
Send, save, and reuse cookies.
Upload and Download
Transfer files to and from a server.
Proxies
Route requests through HTTP or SOCKS proxies.
Follow Redirects
Chase 3xx responses automatically.
Debugging
Trace requests, timing, and transfers.
Was this helpful?