Primeiros passos
Requisições básicas
curl faz requisições HTTP pela linha de comando. Por padrão faz GET. -v mostra saída verbosa, -o salva num arquivo nomeado, -O mantém o nome remoto do arquivo, -L segue redirecionamentos, -I busca apenas headers (requisição 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.comSaída e salvamento
-o escreve o corpo num arquivo nomeado; -O usa o nome remoto do arquivo. --output-dir define o diretório de destino. -s (silencioso) suprime o medidor de progresso e erros — pareie com -S para ainda mostrar erros. Use -D para salvar headers num arquivo enquanto descarta o corpo com -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 e headers
-v (verbose) imprime a conversa completa: '>' é a requisição, '<' é a resposta, '*' é info do curl — tudo vai para o stderr, então o stdout fica limpo para o corpo. -I envia uma requisição HEAD e imprime os headers. -D salva headers num arquivo ou '-' para stdout; combine com -o /dev/null para inspecionar headers sem salvar o corpo.
# 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.comSeguindo redirecionamentos
-L segue redirecionamentos HTTP 3xx; por padrão o curl segue até 50 saltos (use --max-redirs para limitar). RFC 301/302 normalmente converte POST em GET — use --post301/--post302 para preservar a função. Por padrão, credenciais não são enviadas a hosts redirecionados; --location-trusted as envia a qualquer destino (risco de segurança).
# 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.comSintaxe de URL e globbing
O curl expande padrões de 'globbing' de URL: [1-10] faixas, {a,b,c} listas, com um :step opcional. Cada expansão é uma requisição separada. Use -g (--globoff) para tratar colchetes e chaves literalmente — importante para URLs contendo arrays JSON ou endereços 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"Ajuda e versão
--version mostra a versão do curl, os protocolos suportados (HTTP, HTTPS, FTP, etc.) e os recursos compilados (HTTP2, SSL, brotli). --help all lista todas as opções — útil quando você lembra de parte do nome de uma flag. Os recursos dependem de como o curl foi compilado (por exemplo, HTTP/3 precisa de um build 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
Requisições GET
GET é a função padrão. Sempre coloque URLs contendo & ou ? entre aspas para que o shell não as coloque em segundo plano nem as expanda. -X define a função explicitamente, mas geralmente é desnecessário para GET. Para APIs, defina Accept para negociar o formato da resposta.
# 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/secretRequisições POST
Enviar -d muda automaticamente a função para POST, então -X POST é redundante (mas inofensivo e esclarecedor). Para fazer POST de um arquivo, use -d @filename (o @ lê o arquivo). O Content-Type padrão de -d é application/x-www-form-urlencoded; sobrescreva com -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 e PATCH
PUT substitui um recurso inteiro; PATCH aplica uma atualização parcial. Ambos exigem -X porque o curl não tem atalho -d para eles. -T (upload-file) faz streaming de um arquivo como corpo da requisição e é ideal para uploads PUT. Use --data-binary em vez de -d para evitar remover quebras de linha ao enviar arquivos brutos.
# 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 remove um recurso. A maioria das APIs exige autenticação, então inclua -u ou um header Authorization. Algumas APIs aceitam um corpo (motivo, flags de cascata) — adicione -d e um header Content-Type. Use -w '%{http_code}' para verificar o resultado: 204 (No Content) e 200 são sucessos 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 e OPTIONS
-I envia uma requisição HEAD (só headers, sem corpo) — útil para verificar tamanho (Content-Length), tipo (Content-Type) e last-modified sem baixar. OPTIONS revela os verbos permitidos (o header Allow) e é usado para preflight de CORS pelos navegadores. Adicione headers Origin e Access-Control-Request-Method para simular um 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
Definindo headers (-H)
-H (--header) adiciona um header de requisição. Repita -H para múltiplos headers. Um ponto e vírgula final (X-Empty;) envia um valor vazio. @headers.txt lê headers de um arquivo (um 'Name: value' por linha) — prático para manter tokens de Authorization fora do histórico do 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 comuns
Os headers mais comuns: Accept informa ao servidor qual formato você quer; Content-Type descreve o corpo da requisição; Authorization carrega credenciais. --compressed pede ao curl para solicitar respostas comprimidas (gzip, br) e descomprimi-las automaticamente, então você não precisa tratar encoding manualmente.
# 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
Alguns servidores bloqueiam o User-Agent padrão do curl. -A (--user-agent) o define; um -A vazio o remove por completo. A forma longa é -H 'User-Agent: ...'. Muitos sites que bloqueiam scraping verificam assinaturas de navegador real, então um UA de navegador realista costuma ser exigido.
# 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 e Host
-e (--referer) define o header Referer. Sobrescrever o Host é essencial ao testar virtual hosts por IP: o servidor escolhe o site certo com base no Host. Endpoints com consciência de CORS frequentemente exigem Origin; X-Forwarded-For/Proto simulam requisições atrás de um proxy ou 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.comRemovendo headers
Fornecer -H 'Header-Name:' (com dois-pontos, mas sem valor) diz ao curl para não enviar valor para aquele header, efetivamente removendo um header padrão como User-Agent ou Accept-Encoding. O curl substitui um header se você especificar o mesmo nome de novo, em vez de enviar duplicatas. Útil para enviar a requisição mínima possível.
# 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.comDados POST e formulários
Dados de formulário (-d)
-d (--data) envia dados de formulário URL-codificados e muda a função para POST. Múltiplas flags -d são unidas com &. -d remove espaços em branco e quebras de linha no início/fim; --data-binary os preserva; --data-raw desabilita completamente o recurso de @file (então um valor literal começando com @ é enviado como está).
# 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-typeURL-encoding
--data-urlencode faz percent-encoding do valor (ou do name=value inteiro), então você não precisa codificar manualmente espaços, &, = ou não-ASCII. Com name@file, o conteúdo do arquivo é URL-codificado como valor. Use sempre isso para dados fornecidos por usuários para não quebrar a estrutura do formulário.
# 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.comDados binários
--data-binary envia um arquivo byte a byte (preservando quebras de linha e bytes nulos), diferente de -d que os remove. -T faz streaming do arquivo, então o uso de memória permanece baixo para uploads grandes. Para enviar dados pré-comprimidos, faça pipe com -H 'Content-Encoding: gzip' — o servidor precisa suportar; caso contrário use 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/dataLendo de arquivo (@file)
-d @file lê o corpo da requisição de um arquivo (o @ dispara a leitura de arquivo). --data-binary @file preserva os bytes. -d @- lê do stdin — perfeito para fazer pipe de jq, curl ou outras transformações. Se um valor literal começa com @ e você não quer expansão de arquivo, use --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 e formulários
Sempre faça o Content-Type casar com o formato do corpo: application/x-www-form-urlencoded (padrão para -d), application/json (com -H), multipart/form-data (definido automaticamente por -F), text/xml para SOAP. Adicionar charset=utf-8 é boa prática para dados não-ASCII. Incompatibilidades fazem servidores rejeitar ou interpretar mal o corpo.
# 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.comRequisições JSON
POST JSON básico
Requisições JSON precisam de -H 'Content-Type: application/json' mais -d com uma string JSON. Use aspas simples em volta do JSON para que o shell não toque nas aspas duplas internas. Faça pipe da resposta por jq '.' para saída legível, ou jq '.field' para extrair um valor específico.
# 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 de arquivo
Para JSON complexo, guarde-o num arquivo .json e use -d @file (ou --data-binary @file para preservar os bytes exatos, incluindo quebras de linha finais). Fazer pipe de jq -n permite construir JSON programaticamente sem escapes chatos. Sempre valide com jq . primeiro — um erro de sintaxe desperdiça uma requisição.
# 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 com variáveis
Interpolar variáveis em strings JSON quebra em aspas e caracteres especiais. O padrão seguro é jq --arg/--argjson: ele constrói JSON válido e escapa valores corretamente. --arg para strings, --argjson para números/booleanos. Para secrets, prefira um arquivo de headers (-H @file) a argumentos de linha de comando para evitar vazamento via 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.comRequisições GraphQL
GraphQL usa um único endpoint POST com um corpo JSON contendo uma string 'query' e 'variables' opcionais. Escrever a query inline exige escapar as aspas duplas internas, então guarde queries complexas num arquivo .json e use -d @file. Introspecção (a query __schema) lista os tipos da API e é ótima 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 | jqContent negotiation
Accept negocia o formato da resposta; muitas APIs REST retornam JSON por padrão, mas suportam alternativas XML ou CSV. --compressed pede gzip/brotli e descomprime automaticamente. APIs costumam versionar via Accept (por exemplo, GitHub: application/vnd.github+json). Verifique o Content-Type real que o servidor retorna para confirmar que a negociação funcionou.
# 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-typeUpload de arquivos
Upload multipart (-F)
-F (--form) monta uma requisição multipart/form-data — o padrão para uploads de arquivos. -F file=@path lê o arquivo. Adicione ;filename= para sobrescrever o nome que o servidor vê, e ;type= para definir o Content-Type da parte. Múltiplos arquivos no mesmo nome de campo (com [] em muitos frameworks) precisam de múltiplas 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últiplos arquivos e campos
Formulários multipart podem misturar arquivos e campos de texto. Use [] nos nomes de campos para uploads estilo array (frameworks como Rails/PHP interpretam isso como arrays). Um campo pode carregar JSON definindo ;type=application/json — o servidor lê como dado estruturado, não como arquivo. O curl não consegue enviar diretórios nativamente; faça tar antes.
# 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/uploadUpload com streaming (-T)
-T (--upload-file) usa PUT e faz streaming do arquivo, então a memória fica estável mesmo para uploads enormes — muito melhor que -d @file para dados grandes. -T - lê do stdin. -C - retoma uma transferência interrompida. Com uma barra final na URL, o curl anexa o nome do arquivo local (como um HTTP PUT espelhando).
# 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.isoUpload com progresso
Por padrão o curl mostra um medidor de progresso no stderr. --progress-bar troca por uma barra mais simples. -s (silencioso) o oculta; adicione S (-sS) para ainda mostrar erros. A informação de progresso vai para o stderr, então o stdout (o corpo) fica limpo — útil ao fazer pipe. Use -w com %{size_upload} e %{time_total} para um resumo de uma linha.
# 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 e tipos de upload
O curl adivinha o MIME type pela extensão do arquivo. Sobrescreva com ;type=. A opção ;filename= muda o que o servidor vê, útil para nomes sanitizados. O prefixo < lê o conteúdo de um arquivo para um campo de texto (em vez de enviar como arquivo) — ajuda quando a API espera uma string, mas você tem os dados num arquivo.
# 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/uploadAutenticação
Basic Auth (-u)
-u (--user) envia HTTP Basic auth (user:pass codificado em base64). Omita a senha para ser solicitado (mais seguro — mantém fora do histórico do shell). --netrc lê credenciais de ~/.netrc para que nunca apareçam na linha de comando. Basic é inseguro sobre HTTP puro; use sempre HTTPS. Qualquer um com acesso ao shell pode ver os argumentos de -u via 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/secretBearer Token
Bearer tokens (OAuth2, JWT) vão no header Authorization. Evite colocar tokens na linha de comando — ps os expõe a outros usuários. Leia de um arquivo (-H @file) ou variável de ambiente, e use um arquivo de headers para valores sensíveis. O snippet de refresh-token mostra o fluxo padrão OAuth2 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 no header
API keys aparecem em headers personalizados (X-API-Key, X-Client-Id) ou como query parameters. Query strings vazam em logs de servidor e histórico do navegador, então prefira headers. Para AWS, --aws-sigv4 assina a requisição com suas chaves de acesso/secret. GitHub usa Bearer com um 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/dataArquivos Netrc
--netrc lê credenciais de ~/.netrc, mapeando hosts para pares login/password. O arquivo deve ter chmod 600 ou o curl se recusa a usá-lo. --netrc-file aponta para um local personalizado. A entrada 'default' se aplica a qualquer host sem entrada machine específica. Essa é a forma mais limpa de manter secrets fora da linha de comando.
# ~/.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 e NTLM
Basic envia credenciais em texto puro (sobre HTTPS tudo bem). Digest envia um hash, nunca a senha. NTLM e Negotiate tratam SSO de Windows/Kerberos. --anyauth deixa o curl escolher com base no header WWW-Authenticate do servidor. O servidor precisa suportar a função; -v mostra quais desafios ele 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 e tokens
OAuth2 tem vários tipos de grant: client_credentials (servidor a servidor), authorization_code (após um login no navegador), password (legado). O endpoint de token retorna um access_token (e frequentemente um refresh_token); use o access_token como header Bearer nas requisições seguintes. Senhas de app (GitLab, GitHub) funcionam com -u e contornam restrições 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) roteia a requisição por um proxy. As variáveis de ambiente http_proxy/https_proxy/no_proxy são respeitadas automaticamente. Para alvos HTTPS através de um proxy HTTP, o curl usa CONNECT para fazer o túnel. Defina no_proxy para contornar o proxy em hosts internos — separado por vírgulas, com ponto inicial significando subdomínios.
# 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 é agnóstico de protocolo, então faz túnel de HTTP, HTTPS e mais. --socks5-hostname faz o proxy resolver o DNS (útil para alcançar hosts que sua máquina não resolve). Um truque comum: ssh -D 1080 cria um proxy SOCKS local que faz túnel do tráfego por um servidor SSH remoto — ótimo para navegação segura em redes não confiáveis.
# 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.comAutenticação de proxy
Proxies frequentemente exigem autenticação. -U (--proxy-user) fornece credenciais; --proxy-ntlm/--proxy-digest/--proxy-anyauth escolhem o esquema. Embutir user:pass na URL do -x é equivalente. Para NTLM (proxies Windows corporativos), --proxy-ntlm cuida do handshake de múltiplas etapas. -U user (sem senha) solicita interativamente.
# 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.comNo proxy e bypass
--noproxy (ou a variável de ambiente no_proxy) lista hosts que contornam o proxy. Um ponto inicial significa 'este domínio e os subdomínios'. '*' contorna o proxy para tudo. Faixas CIDR funcionam no curl recente. Essencial quando um proxy externo não alcança 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 e tunneling
--proxy-header adiciona headers destinados ao próprio proxy (como Proxy-Authorization), não encaminhados ao alvo. -p (--proxytunnel) força o curl a usar CONNECT mesmo para HTTP puro (normalmente CONNECT é usado só para HTTPS). Útil quando o proxy intercepta HTTP puro e você quer um túnel de ponta a ponta.
# 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
Pulando verificação (--insecure)
-k (--insecure) pula a verificação de certificado — use apenas para certs de dev autoassinados, nunca em produção, pois permite ataques MITM. O padrão verifica tanto a cadeia de certificados quanto o hostname. --resolve permite fixar um IP mantendo o Host/SNI correto — útil para testar um backend específico atrás de um 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
Mutual TLS (mTLS) exige tanto um certificado de cliente (--cert) quanto sua chave privada (--key). PEM é o padrão; --cert-type P12 trata bundles PKCS#12. --pass fornece a senha da chave. --cacert sobrescreve a lista de CAs confiáveis (padrão: store do sistema) — útil para CAs internos. mTLS é comum em setups zero-trust e 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.comVersão TLS
--tlsv1.X define a versão mínima; --tls-max limita. Forçar 1.2+ desabilita protocolos legados (SSLv3, TLS 1.0/1.1) com fraquezas conhecidas. O padrão negocia a versão mais alta suportada por ambos. -v revela a versão negociada e a cifra na linha '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"Ciphers e CA bundle
--ciphers restringe o conjunto de cifras (sintaxe OpenSSL). --cacert aponta para um CA bundle personalizado para verificar servidores com CAs internos/privados — o bundle do sistema (/etc/ssl/certs ou keychain do macOS) é usado por padrão. Se o CA bundle estiver desatualizado, servidores com certs válidos podem ser rejeitados; atualizar o curl (ou o pacote ca-certificates) resolve.
# 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.comInspeção de certificados
Use -v para inspecionar o certificado do servidor (subject, issuer, datas de validade). --pinnedpubkey impõe certificate pinning — a requisição falha se a chave pública do servidor não corresponder, derrotando CAs fraudulentos. Para depuração profunda de TLS, --trace-ascii despeja o handshake completo. openssl s_client é uma alternativa mais poderosa para inspecionar certs.
# 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 certDownload
Salvar em arquivo (-o/-O)
-o escreve num nome de arquivo escolhido; -O usa o nome remoto do arquivo (do basename da URL). --output-dir define a pasta de destino para -O. Múltiplas flags -O baixam múltiplos arquivos numa única invocação. -o /dev/null descarta o corpo — útil para disparar webhooks ou medir tempos sem salvar dados.
# 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/webhookRetomando downloads (-C)
-C - (--continue-at -) retoma um download de onde parou, usando o tamanho do arquivo existente como offset em bytes. O servidor precisa suportar requisições Range (verifique Accept-Ranges: bytes). Combine com --retry para lidar com conexões instáveis — o curl tenta de novo e retoma, evitando desperdício 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 progresso
--progress-bar mostra uma barra ### mais simples em vez do medidor padrão. -s silencia o progresso; -sS mantém os erros. O progresso vai para o stderr, então não polui o corpo no stdout — você pode capturar ambos separadamente. -w com %{size_download} e %{time_total} dá um resumo limpo de uma linha 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.zipFaixa de download
-r (--range) pede uma faixa de bytes, retornando 206 Partial Content. Útil para pré-visualizar arquivos grandes, retomar ou downloads paralelos multi-conexão. O servidor precisa anunciar Accept-Ranges: bytes. Combine com second plano do shell (&) para baixar faixas concorrentemente, depois concatene — a base de aceleradores de download como o 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últiplos arquivos e globbing
URL globbing ([1-3], {a,b,c}) emite uma requisição por expansão. --output-dir define onde -O salva. Para paralelismo real (o curl em si é sequencial), faça pipe das URLs para xargs -P N para rodar N curls em concorrência. Isso acelera muito o download de muitos arquivos pequenos do mesmo host (respeite os rate limits do 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 -OMirror e recursão
O curl é de URL única por design — não recursa. Para espelhar um site, use wget --mirror ou faça script de extração de links com grep. Para downloads em lote, liste as URLs num arquivo e alimente o xargs -P N para paralelismo. O exemplo de sitemap busca e baixa todas as páginas indexadas de um site — prático para snapshots 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 e retentativas
Timeout de conexão
--connect-timeout limita o tempo para estabelecer a conexão TCP/TLS (mas não a transferência). Sem ele, o curl pode travar por minutos em hosts inalcançáveis (padrão do SO ~2 minutos). Sempre defina ambos --connect-timeout (falhar rápido em hosts mortos) e --max-time (limitar a operação inteira) em scripts para evitar travamentos.
# 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.comTempo máximo
--max-time (-m) limita a operação inteira (DNS + conexão + transferência). --speed-time/--speed-limit abortam se a transferência cair abaixo de uma taxa de bytes por um período — perfeito para downloads parados. Código de saída 28 significa timeout; verifique $? em scripts. Sempre defina um max-time para evitar travamentos infinitos em servidores lentos ou presos.
# 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: $?"Retentativas
--retry tenta de novo em erros transitórios (timeouts, 5xx, 429) por padrão; --retry-all-errors estende para todas as falhas. --retry-delay adiciona uma espera fixa (dobra a cada tentativa) entre retentativas. --retry-connrefused tenta mesmo quando a conexão é recusada (por exemplo, servidor reiniciando). Pareie com -C - para retomar downloads parciais. Essencial 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.isoDelay de retry e backoff
--retry-delay N espera N segundos antes da primeira retentativa, depois dobra (N, 2N, 4N...). O curl honra o header Retry-After do servidor para respostas 429/503. Para lógica personalizada (jitter, espera total máxima, condição no código de status), envolva o curl num loop de shell. Sempre pareie --retry com --max-time para que as retentativas não rodem para sempre.
# 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.comLimites de velocidade
--speed-time/--speed-limit aborta uma transferência parada (sem dados por N segundos a uma taxa abaixo do limite) — código de saída 28. --limit-rate limita a taxa de transferência (suporta sufixos K/M/G), útil para não saturar a banda ou para testar redes lentas. Combine com --retry para retomar downloads parados automaticamente.
# 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.isoDepuração
Verboso (-v)
-v (verbose) é a principal ferramenta de depuração. Linhas '>' são a requisição, '<' são a resposta, '*' são internals do curl (DNS, TLS, conexão) — tudo no stderr, então o stdout fica limpo para o corpo. Redirecione 2>&1 para filtrar com grep. Use -o /dev/null para inspecionar headers sem salvar o corpo.
# 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 despeja tudo (incluindo o corpo) em hex + ASCII; --trace-ascii pula o hex. --trace-time adiciona timestamps. Diferente de -v, trace mostra os corpos de requisição e resposta, então é a escolha para depurar dados binários ou comprimidos. Aviso: --trace registra secrets (senhas, tokens) — limpe antes de compartilhar.
# 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 | headSó headers
-I envia uma requisição HEAD (a maioria dos servidores retorna os mesmos headers do GET, sem o corpo). -D despeja headers num arquivo ou '-' (stdout). Para ver o que o curl enviou (headers da requisição), use -v e grep '^>'. Para só o código de status, -w '%{http_code}' é o mais limpo. Nota: alguns servidores respondem diferente a HEAD vs 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 -1Separação de requisição e resposta
A saída verbosa vai para o stderr, o corpo para o stdout, então podem ser capturados separadamente com redirecionamento. -D salva headers de resposta; -o salva o corpo; -v (stderr) captura a conversa completa. Essa separação é essencial para depurar APIs: inspecione headers e corpo de forma independente, registre tempos e compare requisição vs resposta.
# 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.comOpções de depuração
--dry-run imprime o que o curl faria sem enviar — ótimo para verificar globbing de URL e config. --resolve fixa um host a um IP, contornando o DNS (essencial para testar um backend específico). --interface vincula a uma placa de rede ou IP. --no-keepalive força uma conexão nova por requisição, útil para reproduzir bugs no nível de conexão.
# 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].zipInfo da resposta
Código de status HTTP
-w '%{http_code}' extrai só o código de status para scriptar. -f (--fail) faz o curl sair com código não-zero em 4xx/5xx (sem ele, o curl retorna 0 mesmo para 404). --fail-with-body também imprime o corpo da resposta em erro (mais útil para depurar). Use o código de status para ramificar em scripts: 2xx sucesso, 3xx redirecionamento, 4xx erro de cliente, 5xx erro de 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) formata informações sobre a transferência usando placeholders %{variable}. Os timings (time_namelookup, time_connect, time_appconnect, time_total) decompõem onde o tempo é gasto — essencial para análise de desempenho. %{json} gera todas as variáveis como JSON (curl 7.70+). Guarde um formato num arquivo e use -w @file para reutilizar.
# 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.comTempo de resposta
As variáveis de timing decompõem a requisição: time_namelookup (DNS), time_connect (TCP), time_appconnect (TLS), time_starttransfer (TTFB — primeiro byte recebido), time_total (transferência inteira). TTFB é a métrica-chave para latência de API. Compare timings entre endpoints para identificar gargalos (DNS, rede, TLS ou processamento do 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.comExtraindo headers
-D - despeja os headers de resposta no stdout; faça pipe por grep para extrair um header específico. -I (HEAD) também funciona, mas pode diferir do GET. -w fornece %{url_effective} (URL final após redirecionamentos), %{remote_ip} (IP do servidor) e %{num_redirects}. Valiosos para depurar roteamento de CDN, redirecionamentos e identificação de servidores.
# 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/abcVariáveis de formato
-w (--write-out) suporta dezenas de variáveis (rode 'curl -w "%{json}"' para vê-las todas como JSON). As variáveis de timing são a base do monitoramento de desempenho; as de tamanho rastreiam banda; url_effective e num_redirects depuram roteamento. %{json} (curl 7.70+) é a forma mais fácil de capturar tudo para logs ou 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 e SMTP
Básico de FTP
O curl suporta FTP tanto para downloads (GET) quanto para uploads (PUT via -T). -u fornece credenciais; FTP anônimo usa 'anonymous' + um e-mail. FTPS (--ftp-ssl) criptografa o canal de controle. Modo passivo (padrão) funciona através de NAT/firewalls; use --ftp-port para modo ativo se o servidor exigir.
# 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:passUpload FTP
-T envia um arquivo via comando STOR do FTP. --ftp-create-dirs cria diretórios pais com MKD. --append usa APPE para acrescentar a um arquivo existente. -C - retoma um upload interrompido. Globbing ({a,b}) envia múltiplos arquivos numa única invocação. Para diretórios, faça tar antes — FTP não consegue enviar pastas diretamente.
# 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:passListagem FTP
Uma URL FTP terminando em / lista o diretório. --list-only retorna só nomes de arquivos. -v mostra os comandos FTP subjacentes (USER, PASS, PASV, LIST, RETR) — valioso para depurar problemas de permissão ou firewall. O curl não recursa em subdiretórios; use wget --mirror ou um script para downloads FTP recursivos.
# 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 "^\*|^[<>]"Enviando e-mail via SMTP
O curl pode enviar e-mail via SMTP. O corpo (com headers) fica num arquivo passado via -T. --mail-from e --mail-rcpt definem o envelope (separado dos headers To/From no corpo). --ssl-reqd força STARTTLS (porta 587); smtps:// usa TLS implícito (porta 465). Auth via -u (LOGIN/PLAIN). Ótimo para alertas scriptados de servidores sem cliente de e-mail.
# 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 e POP3
O curl pode ler e-mail via IMAP e POP3. A sintaxe da URL inclui pasta, UID e seletores de seção. IMAP suporta busca (?UNSEEN, ?SUBJECT etc.). imaps:// e pop3s:// usam TLS implícito. Nota: o curl é somente leitura para e-mail — pode buscar, mas não enviar via IMAP/POP3 (use SMTP para enviar). O corpo é retornado como texto bruto de mensagem 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 e SFTP
FTP tem três variantes criptografadas: FTPS explícito (--ftp-ssl, upgrade na porta 21), FTPS implícito (ftps://, TLS desde o início na porta 990) e SFTP (sftp://, protocolo completamente diferente sobre SSH na porta 22). SFTP suporta auth por chave via --key (com --pass para chaves criptografadas). SFTP costuma ser preferido a FTPS hoje pela simplicidade e compatibilidade com 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 e lote
Downloads paralelos
O curl em si é sequencial — para baixar concorrentemente, rode múltiplos curls em paralelo via & e wait, ou use xargs -P N para rodar N de uma vez. Isso acelera muito muitos arquivos pequenos. Seja considerado: conexões paralelas demais podem sobrecarregar o servidor ou causar rate limit. 4-8 concorrentes é um padrão razoável.
# 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; waitParalelismo com xargs
xargs -P N roda N processos em concorrência, alimentando cada linha do stdin como argumento. -a lê de um arquivo. -I {} permite colocar a URL em qualquer lugar de um comando. Essa é a forma mais simples de paralelizar downloads do curl sem ferramentas extras. Para throttling consciente de host ou lógica de retry complexa, use um gerenciador de downloads 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>&1URL globbing
Globbing expande URLs em múltiplas requisições: [1-10] faixas (com :step opcional e zero-padding via zeros à esquerda) e listas {a,b,c}. -o 'file#1.zip' usa #1 como contador para nomes de saída personalizados. -g (--globoff) desabilita a expansão — essencial para URLs contendo [ ] ou { } literais (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"Faixa sequencial
Para downloads sequenciais (quando paralelismo sobrecarregaria o servidor ou violaria rate limits), faça loop sobre as URLs no bash. Adicione sleep por cortesia. -sf (silencioso + fail) faz o curl sair com código não-zero em erros HTTP, para que o loop possa interromper cedo. Esse é o padrão seguro para scraping ou crawling: seja respeitoso, adicione delays e trate erros.
# 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 e curl
GNU parallel é mais poderoso que xargs: preserva a ordem da saída, mostra progresso (--bar) e trata argumentos com mais flexibilidade. -j N define concorrência. :::: lê de um arquivo, ::: da linha de comando. Parallel é ideal para testes de API em lote, scraping e benchmarks em que você precisa de saída limpa e ordenada de requisições concorrentes.
# 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.txtArquivos de configuração
Básico do .curlrc
~/.curlrc guarda opções padrão aplicadas a toda invocação do curl. Use nomes longos de opção sem o -- inicial. Uma opção por linha; valores podem ser entre aspas. Isso mantém configurações comuns (timeouts, retentativas, User-Agent) consistentes entre scripts e uso interativo. Sobrescreva por requisição passando a opção explicitamente na linha de comando.
# ~/.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 aboveLocal do arquivo de config
O curl lê ~/.curlrc (ou $CURL_HOME/.curlrc) por padrão. -K (--config) aponta para um arquivo específico; -K - lê do stdin. -q (--disable) pula o arquivo de config por completo — útil quando uma opção padrão quebra uma requisição específica. CURL_HOME realoca o diretório de busca para setups portáveis.
# 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 configConfig com -K
-K carrega opções de um arquivo, perfeito para configs por ambiente (tokens de dev vs prod, timeouts, headers). Guardar secrets num arquivo de config (chmod 600) os mantém fora do histórico do shell e do ps. Múltiplos arquivos -K são processados em ordem, então arquivos posteriores sobrescrevem os anteriores — útil para uma config base mais overrides por ambiente.
# 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.comDefaults comuns
Um ~/.curlrc sólido torna cada invocação do curl mais segura e consistente: timeouts evitam travamentos, retentativas lidam com falhas transitórias, --compressed trata gzip de forma transparente, e um User-Agent reduzido diminui fingerprinting. A linha write-out registra timing e status de cada requisição — valioso para checagens rápidas de desempenho.
# ~/.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últiplas configs
Dividir a config em arquivos em camadas (base, auth, api, ambiente) mantém tudo modular e seguro. Processe-os com múltiplas flags -K em ordem — arquivos posteriores sobrescrevem os anteriores. Coloque secrets num arquivo com permissão 600 fora do controle de versão. Um script wrapper que carrega a pilha permite chamar 'mycurl' com os defaults 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 avançadas
Reutilização de conexão
Dentro de uma única invocação do curl, a conexão TCP é reutilizada entre múltiplas URLs do mesmo host (HTTP keep-alive), economizando o overhead do handshake TLS. --no-keepalive desabilita isso. --max-connects limita conexões concorrentes para buscas multi-URL. Entre chamadas separadas do curl, não há reutilização de conexão — para isso, use um cliente persistente como httpie ou um script em 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 e HTTP/3
HTTP/2 multiplexa requisições numa única conexão; HTTP/3 usa QUIC sobre UDP, eliminando o bloqueio head-of-line. --http2 negocia via ALPN sobre TLS; --http2-prior-knowledge pula a negociação (para h2c em texto puro). --http3 exige um build especial do curl. Verifique %{http_version} para confirmar o que foi realmente usado. A maioria das CDNs modernas suporta h2 por padrão.
# 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.comRequisições condicionais
Requisições condicionais economizam banda: o servidor retorna 304 Not Modified (sem corpo) se o recurso não mudou. -z (--time-cond) define If-Modified-Since a partir de uma data ou do mtime de um arquivo local. Para cache baseado em ETag, defina If-None-Match manualmente. If-Unmodified-Since habilita concorrência otimista — o PUT falha se outra pessoa modificou o 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/dataInterface e DNS
--interface vincula a uma placa de rede ou IP — útil em máquinas multi-homed. --resolve fixa um host a um IP, contornando o DNS, ótimo para testar backends atrás de um balanceador. --doh-url usa DNS-over-HTTPS (privacidade). -4/-6 forçam uma família de IP. Happy Eyeballs (padrão) tenta IPv4 e IPv6 para evitar delays de blackhole 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.comRequisições Range e parciais
Requisições Range (-r) buscam parte de um arquivo, retornando 206 Partial Content. Casos de uso: pré-visualizar arquivos grandes, downloads paralelos multi-conexão (dividir em faixas, buscar em concorrência, concatenar) e retomar transferências interrompidas (-C -). O servidor precisa anunciar Accept-Ranges: bytes. É a base de aceleradores de download como o 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 saída
Os códigos de saída do curl distinguem modos de falha: 6 (DNS), 7 (conexão), 22 (erro HTTP, só com -f), 28 (timeout), 35 (TLS), 60 (cert). Use-os para construir scripts robustos que tentam de novo adequadamente (por exemplo, retry no 28, mas falhar rápido no 6). --fail-with-body retorna o corpo da resposta mesmo em 4xx/5xx, tornando a depuração de erros de API muito mais 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.comSnippets 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?