시작하기
기본 요청
curl은 커맨드라인에서 HTTP 요청을 보냅니다. 기본값은 GET입니다. -v는 상세 출력을, -o는 지정한 파일에 저장을, -O는 원격 파일명 유지를, -L은 리다이렉트 추적을, -I는 헤더만 가져오기(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.com출력 & 저장
-o는 본문을 지정한 파일에 쓰고, -O는 원격 파일명을 사용합니다. --output-dir는 저장 디렉터리를 지정합니다. -s(silent)는 진행 표시와 에러를 숨기며, -S를 함께 쓰면 에러는 여전히 보여줍니다. -D로 헤더를 파일에 덤프하고 -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.com상세 출력 & 헤더
-v(verbose)는 전체 대화를 출력합니다: '>'는 요청, '<'는 응답, '*'는 curl 정보이며 모두 stderr로 나가므로 본문이 담기는 stdout은 깨끗하게 유지됩니다. -I는 HEAD 요청을 보내 헤더를 출력합니다. -D는 헤더를 파일이나 '-'(stdout)로 덤프하며, -o /dev/null과 결합하면 본문을 저장하지 않고 헤더만 검사할 수 있습니다.
# 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.com리다이렉트 추적
-L은 HTTP 3xx 리다이렉트를 따르고, 기본적으로 최대 50홉까지 따릅니다(--max-redirs로 제한). RFC 301/302에서는 보통 POST가 GET으로 바뀌는데, 메서드를 유지하려면 --post301/--post302를 사용합니다. 기본적으로 자격 증명은 리다이렉트된 호스트로 전송되지 않으며, --location-trusted는 어디로든 전송합니다(보안 위험).
# 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.comURL 문법 & 글로빙
curl은 URL '글로빙' 패턴을 확장합니다: [1-10] 범위, {a,b,c} 목록, 선택적 :step. 각 확장은 별도의 요청입니다. 대괄호와 중괄호를 문자 그대로 취급하려면 -g(--globoff)를 사용하세요 — JSON 배열이나 http://[::1]:8080/ 같은 IPv6 주소가 들어간 URL에서 중요합니다.
# 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"도움말 & 버전
--version은 curl 버전, 지원 프로토콜(HTTP, HTTPS, FTP 등), 빌드에 포함된 기능(HTTP2, SSL, brotli)을 보여줍니다. --help all은 모든 옵션을 나열합니다 — flag 이름의 일부만 기억할 때 유용합니다. 기능은 curl이 빌드된 방식에 따라 다릅니다(예: HTTP/3은 특별한 빌드가 필요).
# 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 http2HTTP 메서드
GET 요청
GET이 기본 메서드입니다. &나 ?가 들어간 URL은 셸이 백그라운 드 처리하거나 확장하지 않도록 항상 따옴표로 감싸세요. -X는 메서드를 명시하지만 GET에는 보통 불필요합니다. API 호출 시 Accept 헤더로 응답 형식을 협상하세요.
# 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/secretPOST 요청
-d를 쓰면 자동으로 메서드가 POST로 바뀌므로 -X POST는 중복입니다(무해하고 의미를 명확히 하긴 합니다). 파일을 POST하려면 -d @filename을 사용하세요(@가 파일을 읽습니다). -d의 기본 Content-Type은 application/x-www-form-urlencoded이며, JSON을 보낼 때는 -H로 덮어쓰세요.
# 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 & PATCH
PUT은 리소스 전체를 교체하고, PATCH는 부분 업데이트를 적용합니다. 둘 다 curl에 -d 단축이 없으므로 -X가 필요합니다. -T(upload-file)는 파일을 요청 본문으로 스트리밍하며 PUT 업로드에 이상적입니다. 원본 파일을 그대로 보낼 때 -d가 개행을 제거하지 않게 하려면 --data-binary를 사용하세요.
# 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는 리소스를 제거합니다. 대부분의 API는 인증을 요구하므로 -u나 Authorization 헤더를 포함하세요. 일부 API는 본문(사유, 캐스케이드 flag)을 받으므로 -d와 Content-Type 헤더를 추가합니다. 결과 확인은 -w '%{http_code}'로 하세요: 204(No Content)와 200이 일반적인 성공입니다.
# 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 & OPTIONS
-I는 HEAD 요청(본문 없이 헤더만)을 보냅니다 — 다운로드 없이 크기(Content-Length), 타입(Content-Type), last-modified를 확인할 때 유용합니다. OPTIONS는 허용된 메서드(Allow 헤더)를 알려주며, 브라우저의 CORS 프리플라이트에 사용됩니다. Origin과 Access-Control-Request-Method 헤더를 추가하면 실제 프리플라이트를 흉내 낼 수 있습니다.
# 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 allow헤더
헤더 설정 (-H)
-H(--header)는 요청 헤더를 추가합니다. 헤더가 여러 개면 -H를 반복하세요. 뒤에 세미콜론을 붙이면(X-Empty;) 빈 값이 전송됩니다. @headers.txt는 파일(한 줄에 'Name: value')에서 헤더를 읽습니다 — Authorization 토큰을 셸 히스토리에 남기지 않는 데 유용합니다.
# 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.com자주 쓰는 헤더
가장 흔한 헤더들: Accept는 원하는 형식을 서버에 알리고, Content-Type은 요청 본문을 설명하며, Authorization은 자격 증명을 담습니다. --compressed는 압축 응답(gzip, br)을 요청하고 자동으로 해제하므로 인코딩을 직접 다룰 필요가 없습니다.
# 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
일부 서버는 curl의 기본 User-Agent를 차단합니다. -A(--user-agent)로 설정하고, 빈 -A는 완전히 제거합니다. 긴 형식은 -H 'User-Agent: ...'입니다. 스크래핑 차단 사이트는 실제 브라우저 시그니처를 검사하므로 현실적인 브라우저 UA가 필요할 때가 많습니다.
# 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 & Host
-e(--referer)는 Referer 헤더를 설정합니다. IP로 가상 호스트를 테스트할 때는 Host 오버라이드가 필수입니다 — 서버가 Host로 올바른 사이트를 고르기 때문입니다. CORS 지원 엔드포인트는 Origin을 요구할 때가 많고, X-Forwarded-For/Proto는 프록시나 로드밸런서 뒤의 요청을 흉내 냅니다.
# 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.com헤더 제거
-H 'Header-Name:'(콜론만 있고 값이 없음)은 curl에게 해당 헤더를 값 없이 보내라고 지시 합니다 — User-Agent나 Accept-Encoding 같은 기본 헤더를 사실상 제거합니다. curl은 같은 이름을 다시 지정하면 중복으로 보내지 않고 헤더를 교체합니다. 최소한의 요청을 보낼 때 유용합니다.
# 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.comPOST 데이터 & 폼
폼 데이터 (-d)
-d(--data)는 URL 인코딩된 폼 데이터를 보내고 메서드를 POST로 바꿉니다. 여러 -d flag는 &로 연결됩니다. -d는 앞뒤 공백과 개행을 제거하고, --data-binary는 이를 보존하며, --data-raw는 @file 기능을 완전히 비활성화합니다(그래서 @로 시작하는 리터럴 값도 그대로 전송됩니다).
# 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 인코딩
--data-urlencode는 값(또는 name=value 전체)을 퍼센트 인코딩하므로 공백, &, =, 비 ASCII 문자를 직접 인코딩할 필요가 없습니다. name@file 형태로 쓰면 파일 내용이 값으로 URL 인코딩됩니다. 사용자 입력 데이터에는 항상 이 옵션을 써서 폼 구조가 깨지지 않게 하세요.
# 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.com바이너리 데이터
--data-binary는 -d와 달리 파일을 바이트 단위 그대로 보냅니다(개행과 널 바이트 보존). -T는 파일을 스트리밍하므로 큰 업로드에서도 메모리 사용이 낮게 유지됩니다. 미리 압축된 데이터를 보내려면 -H 'Content-Encoding: gzip'과 함께 파이프로 넣으세요 — 서버가 지원해야 하며, 그렇지 않으면 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/data파일에서 읽기 (@file)
-d @file은 파일에서 요청 본문을 읽습니다(@가 파일 읽기를 트리거). --data-binary @file은 바이트를 보존합니다. -d @-는 stdin에서 읽습니다 — jq나 다른 변환 결과를 파이프로 넣기에 완벽합니다. 리터럴 값이 @로 시작하지만 파일 확장을 원치 않으면 --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 & 폼
Content-Type은 본문 형식과 항상 일치시키세요: application/x-www-form-urlencoded(-d 기본값), application/json(-H와 함께), multipart/form-data(-F가 자동 설정), SOAP에는 text/xml. 비 ASCII 데이터에는 charset=utf-8을 붙이는 게 좋습니다. 불일치하면 서버가 본문을 거부하거나 잘못 해석합니다.
# 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.comJSON 요청
기본 JSON POST
JSON 요청에는 -H 'Content-Type: application/json'과 JSON 문자열이 담긴 -d가 필요합니다. 셸이 안쪽의 큰따옴표를 건드리지 않도록 JSON은 작은따옴표로 감싸세요. 응답을 jq '.'으로 파이프하면 읽기 쉬워지고, jq '.field'로 특정 값을 추출할 수 있습니다.
# 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
복잡한 JSON은 .json 파일에 저장하고 -d @file(또는 마지막 개행까지 정확한 바이트를 보존하는 --data-binary @file)로 보내세요. jq -n을 파이프로 쓰면 번거로운 이스케이프 없이 프로그래밍 방식으로 JSON을 만들 수 있습니다. 먼저 jq .로 검증하세요 — 문법 오류는 요청 하나를 낭비합니다.
# 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/batch변수와 JSON
JSON 문자열에 변수를 직접 삽입하면 따옴표와 특수 문자에서 깨집니다. 안전한 패턴은 jq --arg/--argjson입니다: 유효한 JSON을 만들고 값을 올바르게 이스케이프합니다. 문자열은 --arg, 숫자/불리언은 --argjson을 씁니다. 시크릿은 ps를 통해 노출되지 않도록 명령줄 인수 대신 헤더 파일(-H @file)을 권합니다.
# 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.comGraphQL 요청
GraphQL은 'query' 문자열과 선택적 'variables'를 담은 JSON 본문으로 단일 POST 엔드포인트를 사용합니다. 쿼리를 인라인으로 쓰면 안쪽 큰따옴표를 이스케이프해야 하므로, 복잡한 쿼리는 .json 파일에 저장하고 -d @file로 보내세요. 인트로스펙션(__schema 쿼리)은 API의 타입을 나열해 주며 탐색에 유용합니다.
# 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 | jq콘텐츠 협상
Accept가 응답 형식을 협상합니다; 많은 REST API가 기본적으로 JSON을 돌려주지만 XML이나 CSV도 지원합니다. --compressed는 gzip/brotli를 요청하고 자동으로 풀어줍니다. API는 흔히 Accept로 버전을 구분합니다(예: GitHub의 application/vnd.github+json). 협상이 제대로 됐는지는 서버가 돌려준 실제 Content-Type으로 확인하세요.
# 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-type파일 업로드
멀티파트 업로드 (-F)
-F(--form)는 multipart/form-data 요청을 만듭니다 — 파일 업로드의 표준입니다. -F file=@path가 파일을 읽습니다. ;filename=으로 서버가 보는 이름을 바꾸고, ;type=으로 파트의 Content-Type을 설정할 수 있습니다. 같은 필드 이름으로 여러 파일(많은 프레임워크에서 [])을 보내려면 -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/upload여러 파일 & 필드
멀티파트 폼은 파일과 텍스트 필드를 섞을 수 있습니다. 배열식 업로드에는 필드 이름에 []를 쓰세요(Rails/PHP 같은 프레임워크가 배열로 파싱합니다). ;type=application/json을 설정하면 필드가 JSON을 담을 수 있습니다 — 서버가 파일이 아닌 구조화된 데이터로 읽습니다. curl은 디렉터리를 직접 업로드할 수 없으니 먼저 tar로 묶으세요.
# 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/upload스트리밍 업로드 (-T)
-T(--upload-file)는 PUT을 사용하며 파일을 스트리밍하므로, 거대한 업로드에서도 메모리가 일정하게 유지됩니다 — 큰 데이터에는 -d @file보다 훨씬 좋습니다. -T -는 stdin에서 읽습니다. -C -는 중단된 전송을 재개합니다. URL 끝에 슬래시를 붙이면 curl이 로컬 파일명을 덧붙입니다(HTTP PUT 미러링처럼).
# 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.iso진행 표시와 업로드
기본적으로 curl은 stderr에 진행 표시를 보여줍니다. --progress-bar는 더 단순한 바로 바꿉니다. -s(silent)는 숨기고, S를 더하면(-sS) 에러는 여전히 보입니다. 진행 정보는 stderr로 나가므로 stdout(본문)은 깨끗합니다 — 파이프할 때 유용합니다. 한 줄 요약에는 -w와 %{size_upload}, %{time_total}을 사용하세요.
# 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/upload업로드 필드 & 타입
curl은 파일 확장자로 MIME 타입을 추측합니다. ;type=으로 덮어쓰세요. ;filename= 옵션은 서버가 보는 이름을 바꾸며, 정제된 이름을 쓸 때 유용합니다. < 접두사는 파일 내용을 텍스트 필드로 읽어 들입니다(파일로 전송하지 않음) — API가 문자열을 기대하는데 데이터가 파일에 있을 때 유용합니다.
# 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/upload인증
Basic 인증 (-u)
-u(--user)는 HTTP Basic 인증(base64 인코딩된 user:pass)을 보냅니다. 비밀번호를 생략하면 프롬프트로 물어봅니다(셸 히스토리에 남지 않아 더 안전합니다). --netrc는 ~/.netrc에서 자격 증명을 읽어 명령줄에 노출되지 않게 합니다. Basic은 평문 HTTP에서는 안전하지 않으니 항상 HTTPS를 쓰세요. 셸 접근 권한이 있는 누구나 ps로 -u 인수를 볼 수 있습니다.
# 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 토큰
Bearer 토큰(OAuth2, JWT)은 Authorization 헤더에 넣습니다. 토큰을 명령줄에 두지 마세요 — ps가 다른 사용자에게 노출합니다. 파일(-H @file)이나 환경 변수에서 읽고, 민감한 값은 헤더 파일을 사용하세요. refresh-token 스니펫은 표준 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/data헤더의 API 키
API 키는 커스텀 헤더(X-API-Key, X-Client-Id)나 쿼리 파라미터로 전달됩니다. 쿼리 문자열은 서버 로그와 브라우저 히스토리에 남으므로 헤더를 권합니다. AWS에서는 --aws-sigv4가 access/secret 키로 요청에 서명합니다. GitHub는 개인 액세스 토큰(ghp_...)으로 Bearer를 사용합니다.
# 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/dataNetrc 파일
--netrc는 ~/.netrc에서 호스트별 login/password 쌍을 읽습니다. 파일은 chmod 600이어야 하며, 그렇지 않으면 curl이 사용을 거부합니다. --netrc-file은 커스텀 위치를 지정합니다. 'default' 항목은 특정 machine 항목이 없는 모든 호스트에 적용됩니다. 시크릿을 명령줄에서 치우는 가장 깔끔한 방법입니다.
# ~/.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 & NTLM
Basic은 자격 증명을 평문으로 보냅니다(HTTPS 위에서는 괜찮습니다). Digest는 해시를 보내며 비밀번호는 절대 보내지 않습니다. NTLM과 Negotiate는 Windows/Kerberos SSO를 처리합니다. --anyauth는 서버의 WWW-Authenticate 헤더에 따라 curl이 선택하게 합니다. 서버가 해당 방식을 지원해야 하며, -v로 어떤 챌린지를 내는지 볼 수 있습니다.
# 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 & 토큰
OAuth2에는 여러 그랜트 타입이 있습니다: client_credentials(서버 간), authorization_code(브라우저 로그인 후), password(레거시). 토큰 엔드포인트는 access_token(그리고 보통 refresh_token)을 반환하며, 이후 요청에서 access_token을 Bearer 헤더로 사용합니다. 앱 비밀번호(GitLab, GitHub)는 -u로 동작하며 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/user프록시
HTTP/HTTPS 프록시
-x(--proxy)는 요청을 프록시로 라우팅합니다. http_proxy/https_proxy/no_proxy 환경 변수는 자동으로 존중됩니다. HTTP 프록시를 통해 HTTPS 대상에 접속할 때 curl은 CONNECT로 터널을 만듭니다. 내부 호스트는 프록시를 우회하도록 no_proxy를 설정하세요 — 쉼표로 구분하며, 앞의 점은 서브도메인 포함을 의미합니다.
# 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 proxySOCKS 프록시
SOCKS5는 프로토콜 독립적이라 HTTP, HTTPS 등을 터널링합니다. --socks5-hostname은 프록시가 DNS를 풀게 합니다(내 머신이 해석 못 하는 호스트에 도달할 때 유용). 흔한 트릭: ssh -D 1080은 원격 SSH 서버로 트래픽을 터널링하는 로컬 SOCKS 프록시를 만듭니다 — 신뢰할 수 없는 네트워크에서의 안전한 브라우징에 좋습니다.
# 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.com프록시 인증
프록시는 인증을 요구하는 경우가 많습니다. -U(--proxy-user)가 자격 증명을 제공하고, --proxy-ntlm/--proxy-digest/--proxy-anyauth가 방식을 고릅니다. -x URL에 user:pass를 넣는 것도 동일합니다. NTLM(기업 Windows 프록시)에서는 --proxy-ntlm이 다단계 핸드셰이크를 처리합니다. -U user(비밀번호 없음)는 대화형으로 물어봅니다.
# 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.com프록시 우회
--noproxy(또는 no_proxy 환경 변수)는 프록시를 우회할 호스트를 나열합니다. 앞의 점은 '이 도메인과 모든 서브도메인'을 의미하고, '*'는 모든 대상을 우회합니다. 최근 curl은 CIDR 범위도 지원합니다. 외부 프록시가 내부 기업 호스트에 도달할 수 없을 때 필수입니다.
# 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"프록시 헤더 & 터널링
--proxy-header는 대상에 전달되지 않고 프록시 자체를 위한 헤더(Proxy-Authorization 등)를 추가합니다. -p(--proxytunnel)는 평문 HTTP에도 CONNECT를 강제합니다(보통 CONNECT는 HTTPS에만 사용). 프록시가 평문 HTTP를 가로채는 상황에서 엔드투엔드 터널을 원할 때 유용합니다.
# 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
검증 건너뛰기 (--insecure)
-k(--insecure)는 인증서 검증을 건너뜁니다 — 자체 서명된 개발용 인증서에만 쓰고, MITM 공격을 허용하므로 프로덕션에서는 절대 금지입니다. 기본값은 인증서 체인과 호스트명을 모두 검증합니다. --resolve는 올바른 Host/SNI를 유지하면서 IP를 고정합니다 — 로드밸런서 뒤의 특정 백엔드를 테스트할 때 유용합니다.
# 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"클라이언트 인증서
상호 TLS(mTLS)에는 클라이언트 인증서(--cert)와 그 개인 키(--key)가 모두 필요합니다. 기본은 PEM이고, --cert-type P12가 PKCS#12 번들을 처리합니다. --pass는 키 비밀번호를 제공합니다. --cacert는 신뢰하는 CA 목록을 교체합니다(기본: 시스템 스토어) — 내부 CA에 유용합니다. mTLS는 제로 트러스트와 서비스 메시 환경에서 흔합니다.
# 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.comTLS 버전
--tlsv1.X는 최소 버전을, --tls-max는 상한을 설정합니다. 1.2 이상을 강제하면 알려진 취약점이 있는 레거시 프로토콜(SSLv3, TLS 1.0/1.1)이 비활성화됩니다. 기본값은 서로 지원하는 가장 높은 버전을 협상합니다. -v는 '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"암호 스위트 & CA 번들
--ciphers는 암호 스위트를 제한합니다(OpenSSL 문법). --cacert는 내부/사설 CA로 서버를 검증하기 위한 커스텀 CA 번들을 가리킵니다 — 기본은 시스템 번들(/etc/ssl/certs 또는 macOS 키체인)입니다. CA 번들이 오래됐으면 유효한 인증서를 가진 서버도 거부될 수 있고, curl(또는 ca-certificates 패키지)을 업데이트하면 해결됩니다.
# 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.com인증서 검사
-v로 서버 인증서(subject, issuer, 유효 기간)를 검사할 수 있습니다. --pinnedpubkey는 인 증서 피닝을 강제합니다 — 서버의 공개 키가 일치하지 않으면 요청이 실패해 무단 CA를 무력화합니다. 깊은 TLS 디버깅에는 --trace-ascii가 전체 핸드셰이크를 덤프합니다. 인증서 검사에는 openssl s_client가 더 강력한 대안입니다.
# 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 cert다운로드
파일 저장 (-o/-O)
-o는 지정한 파일명으로 쓰고, -O는 원격 파일명(URL의 basename)을 사용합니다. --output-dir는 -O의 저장 폴더를 지정합니다. -O를 여러 번 쓰면 한 번의 실행으로 여러 파일을 내려받습니다. -o /dev/null은 본문을 버립니다 — 데이터를 저장하지 않고 웹훅을 트리거하거나 시간을 측정할 때 유용합니다.
# 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/webhook다운로드 재개 (-C)
-C -(--continue-at -)는 기존 파일 크기를 바이트 오프셋으로 써서 중단된 지점부터 다운로드를 재개합니다. 서버가 Range 요청을 지원해야 합니다(Accept-Ranges: bytes 확인). 불안정한 연결에는 --retry와 결합하세요 — curl이 재시도하고 재개해 낭비 대역폭을 피합니다.
# 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.iso진행 바
--progress-bar는 기본 미터 대신 단순한 ### 바를 보여줍니다. -s는 모든 진행 표시를 끄고, -sS는 에러를 유지합니다. 진행 정보는 stderr로 나가므로 stdout의 본문을 오염시키지 않습니다 — 둘을 따로 캡처할 수 있습니다. 스크립트용 깔끔한 한 줄 요약에는 -w와 %{size_download}, %{time_total}을 쓰세요.
# 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.zip범위 다운로드
-r(--range)은 바이트 범위를 요청해 206 Partial Content를 받습니다. 큰 파일 미리보기, 재개, 병렬 다중 연결 다운로드에 유용합니다. 서버가 Accept-Ranges: bytes를 알려야 합니다. 셸 백그라운드(&)와 결합해 범위를 동시에 내려받고 이어 붙이면 — 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 HTTP여러 파일 & 글로빙
URL 글로빙([1-3], {a,b,c})은 확장마다 요청 하나를 보냅니다. --output-dir는 -O가 저장할 위치를 정합니다. 진짜 병렬성(curl 자체는 순차 실행)을 원하면 URL을 xargs -P N에 파이프해 N개의 curl을 동시에 실행하세요. 같은 호스트에서 많은 작은 파일을 내려받을 때 속도가 크게 빨라집니다(서버의 레이트 리밋은 존중하세요).
# 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 -O미러 & 재귀
curl은 단일 URL이 설계 철학이라 재귀하지 않습니다. 사이트를 미러링하려면 wget --mirror를 쓰거나 grep으로 링크 추출을 스크립트화하세요. 대량 다운로드에는 URL을 파일에 나열하고 xargs -P N으로 병렬화합니다. sitemap 예제는 사이트가 색인한 모든 페이지를 가져와 내려받습니다 — 오프라인 스냅샷에 유용합니다.
# 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 -O타임아웃 & 재시도
연결 타임아웃
--connect-timeout은 TCP/TLS 연결 수립 시간을 제한합니다(전송 시간은 아님). 없으면 도달 불가능한 호스트에서 curl이 몇 분씩 멈출 수 있습니다(OS 기본 약 2분). 스크립트에서는 항상 --connect-timeout(죽은 호스트에서 빠른 실패)과 --max-time(전체 작업 상한)을 함께 설정해 멈춤을 피하세요.
# 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.com최대 시간
--max-time(-m)은 전체 작업(DNS + 연결 + 전송)을 제한합니다. --speed-time/--speed-limit은 전송 속도가 일정 시간 동안 한도 아래로 떨어지면 중단합니다 — 멈춘 다운로드에 완벽합니다. 종료 코드 28은 타임아웃이므로 스크립트에서 $?를 확인하세요. 느리거나 멈춘 서버에서 무한 대기하지 않도록 항상 max-time을 설정하세요.
# 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: $?"재시도
--retry는 기본적으로 일시적 오류(타임아웃, 5xx, 429)에서 재시도하고, --retry-all-errors는 모든 실패로 확장합니다. --retry-delay는 재시도 사이에 고정 대기(시도마다 두 배)를 추가합니다. --retry-connrefused는 연결 거부(예: 서버 재시작 중)에도 재시도합니다. 부분 다운로드 재개에는 -C -와 결합하세요. 회복력 있는 스크립트에 필수입니다.
# 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.iso재시도 지연 & 백오프
--retry-delay N은 첫 재시도 전 N초를 기다린 뒤 두 배씩 늘어납니다(N, 2N, 4N...). curl은 429/503 응답에서 서버의 Retry-After 헤더를 존중합니다. 커스텀 로직(지터, 총 대기 상한, 상태 코드 조건)에는 curl을 셸 루프로 감싸세요. 재시도가 영원히 돌지 않도록 --retry에는 항상 --max-time을 짝지으세요.
# 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.com속도 제한
--speed-time/--speed-limit은 멈춘 전송(한도 아래 속도로 N초간 데이터 없음)을 중단합니다 — 종료 코드 28. --limit-rate는 전송 속도를 제한합니다(K/M/G 접미사 지원) — 대역폭을 포화시키지 않거나 느린 네트워크를 테스트할 때 유용합니다. --retry와 결합하면 멈춘 다운로드를 자동으로 재개합니다.
# 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.iso디버깅
상세 출력 (-v)
-v(verbose)는 1차 디버깅 도구입니다. '>' 줄은 요청, '<' 줄은 응답, '*' 줄은 curl 내부(DNS, TLS, 연결)이며 모두 stderr로 나가므로 stdout의 본문은 깨끗합니다. 2>&1로 합쳐 grep으로 필터링하세요. -o /dev/null로 본문을 저장하지 않고 헤더를 검사할 수 있습니다.
# 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.com트레이스
--trace는 본문 포함 모든 것을 16진수+ASCII로 덤프하고, --trace-ascii는 16진수를 생략합니다. --trace-time은 타임스탬프를 추가합니다. -v와 달리 trace는 요청/응답 본문을 보여주므로 바이너리나 압축 데이터 디버깅에 필수입니다. 경고: --trace는 시크릿(비밀번호, 토큰)을 기록합니다 — 공유 전에 걸러내세요.
# 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 | head헤더만 보기
-I는 HEAD 요청을 보냅니다(대부분의 서버가 본문 없이 GET과 같은 헤더를 돌려줍니다). -D는 헤더를 파일이나 '-'(stdout)로 덤프합니다. curl이 보낸 것(요청 헤더)을 보려면 -v에서 grep '^>'를 쓰세요. 상태 코드만이라면 -w '%{http_code}'가 가장 깔끔합니다. 참고: 일부 서버는 HEAD와 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 -1요청 & 응답 분리
상세 출력은 stderr로, 본문은 stdout으로 나가므로 리다이렉션으로 따로 캡처할 수 있습니다. -D는 응답 헤더를 저장하고, -o는 본문을 저장하며, -v(stderr)는 전체 대화를 캡처합니다. 이 분리는 API 디버깅에 필수입니다: 헤더와 본문을 독립적으로 검사하고, 시간을 기록하고, 요청과 응답을 비교합니다.
# 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.com디버그 옵션
--dry-run은 전송 없이 curl이 할 일을 출력합니다 — URL 글로빙과 설정 검증에 좋습니다. --resolve는 DNS를 우회해 호스트를 IP에 고정합니다(특정 백엔드 테스트에 필수). --interface는 네트워크 카드나 IP에 바인딩합니다. --no-keepalive는 요청마다 새 연결을 강제해 연결 수준 버그를 재현할 때 유용합니다.
# 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].zip응답 정보
HTTP 상태 코드
-w '%{http_code}'는 스크립팅을 위해 상태 코드만 추출합니다. -f(--fail)는 4xx/5xx에서 0이 아닌 종료 코드를 돌려줍니다(없으면 404여도 curl은 0을 반환). --fail-with-body는 에러 시에도 응답 본문을 출력합니다(디버깅에 더 유용). 스크립트 분기에는 상태 코드를 쓰세요: 2xx 성공, 3xx 리다이렉트, 4xx 클라이언트 오류, 5xx 서버 오류.
# 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/abcwrite-out 형식
-w(--write-out)는 %{variable} 플레이스홀더로 전송 정보를 포맷합니다. 타이밍(time_namelookup, time_connect, time_appconnect, time_total)은 시간이 어디에 쓰였는지 분해해 줍니다 — 성능 분석에 필수입니다. %{json}은 모든 변수를 JSON으로 출력합니다(curl 7.70+). 재사용할 형식은 파일에 저장하고 -w @file로 쓰세요.
# 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.com응답 시간
타이밍 변수들은 요청을 분해합니다: time_namelookup(DNS), time_connect(TCP), time_appconnect(TLS), time_starttransfer(TTFB — 첫 바이트 수신), time_total(전체 전송). TTFB가 API 지연의 핵심 지표입니다. 엔드포인트 간 타이밍을 비교해 병목(DNS, 네트워크, TLS, 서버 처리)을 찾아내세요.
# 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.com헤더 추출
-D -는 응답 헤더를 stdout으로 덤프하며, grep으로 파이프해 특정 헤더를 뽑을 수 있습니다. -I(HEAD)도 되지만 GET과 다를 수 있습니다. -w는 %{url_effective}(리다이렉트 후 최종 URL), %{remote_ip}(서버 IP), %{num_redirects}를 제공합니다. CDN 라우팅, 리다이렉트, 서버 식별 디버깅에 매우 유용합니다.
# 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/abc형식 변수
-w(--write-out)는 수십 개의 변수를 지원합니다('curl -w "%{json}"'으로 전체를 JSON으로 볼 수 있습니다). 타이밍 변수는 성능 모니터링의 기초이고, size 변수는 대역폭을 추적하며, url_effective와 num_redirects는 라우팅 디버깅에 씁니다. %{json}(curl 7.70+)은 로깅이나 대시보드용으로 모든 것을 캡처하는 가장 쉬운 방법입니다.
# 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 & SMTP
FTP 기본
curl은 다운로드(GET)와 업로드(-T로 PUT) 모두 FTP를 지원합니다. -u가 자격 증명을 제공하고, 익명 FTP는 'anonymous' + 이메일을 씁니다. FTPS(--ftp-ssl)는 제어 채널을 암호화합니다. 패시브 모드(기본값)는 NAT/방화벽을 통과하며, 서버가 요구하면 --ftp-port로 액티브 모드를 씁니다.
# 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:passFTP 업로드
-T는 FTP의 STOR 명령으로 파일을 업로드합니다. --ftp-create-dirs는 MKD로 상위 디렉터리를 만듭니다. --append는 APPE로 기존 파일에 덧붙입니다. -C -는 중단된 업로드를 재개합니다. 글로빙({a,b})으로 한 번에 여러 파일을 업로드합니다. 디렉터리는 먼저 tar로 묶으세요 — FTP는 폴더를 직접 업로드할 수 없습니다.
# 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:passFTP 목록
FTP URL이 /로 끝나면 디렉터리를 나열합니다. --list-only는 파일명만 돌려줍니다. -v는 하위 FTP 명령(USER, PASS, PASV, LIST, RETR)을 보여줍니다 — 권한이나 방화벽 문제 디버깅에 매우 유용합니다. curl은 서브디렉터리로 재귀하지 않으므로, 재귀 FTP 다운로드에는 wget --mirror나 스크립트를 쓰세요.
# 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 "^\*|^[<>]"SMTP 메일 전송
curl은 SMTP로 메일을 보낼 수 있습니다. 헤더를 포함한 본문은 파일에 담아 -T로 파이프합니다. --mail-from과 --mail-rcpt는 봉투(envelope)를 설정합니다(본문의 To/From 헤더와 별개). --ssl-reqd는 STARTTLS를 강제하고(포트 587), smtps://는 암시적 TLS를 씁니다(포트 465). 인증은 -u로(LOGIN/PLAIN). 메일 클라이언트가 없는 서버의 스크립트 경보에 좋습니다.
# 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 & POP3
curl은 IMAP과 POP3로 메일을 읽을 수 있습니다. URL 문법에는 폴더, UID, 섹션 선택자가 포함됩니다. IMAP은 검색을 지원합니다(?UNSEEN, ?SUBJECT 등). imaps://와 pop3s://는 암시적 TLS를 씁니다. 참고: curl은 메일에 읽기 전용입니다 — IMAP/POP3로 가져올 수는 있지만 보낼 수는 없습니다(보내기는 SMTP). 본문은 원본 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 & SFTP
FTP에는 세 가지 암호화 변형이 있습니다: FTPS explicit(--ftp-ssl, 포트 21에서 업그레이드), FTPS implicit(ftps://, 포트 990에서 처음부터 TLS), SFTP(sftp://, 포트 22의 SSH 위에서 완전히 다른 프로토콜). SFTP는 --key로 키 인증을 지원합니다(암호화된 키에는 --pass). 오늘날에는 단순함과 방화벽 친화성 때문에 SFTP가 FTPS보다 선호됩니다.
# 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/병렬 & 배치
병렬 다운로드
curl 자체는 순차 실행입니다 — 동시에 내려받으려면 &와 wait로 여러 curl을 병렬로 돌리거나, xargs -P N으로 N개를 한꺼번에 실행하세요. 많은 작은 파일에서 속도가 크게 빨라집니다. 배려하세요: 너무 많은 동시 연결은 서버를 압도하거나 레이트 리밋에 걸립니다. 4~8개 동시 실행이 무난한 기본값입니다.
# 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; waitxargs 병렬
xargs -P N은 N개 프로세스를 동시에 실행하며 stdin의 각 줄을 인수로 넘깁니다. -a는 파일에서 읽고, -I {}는 커맨드 어디든 URL을 놓게 해 줍니다. 추가 도구 없이 curl 다운로드를 병렬화하는 가장 간단한 방법입니다. 호스트 인식 스로틀링이나 복잡한 재시도 로직에는 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 글로빙
글로빙은 URL을 여러 요청으로 확장합니다: [1-10] 범위(선택적 :step과 선행 0으로 자릿수 고정)와 {a,b,c} 목록. -o 'file#1.zip'은 #1을 카운터로 써 커스텀 출력 이름을 만듭니다. -g(--globoff)는 확장을 비활성화합니다 — 리터럴 [ ]이나 { }이 들어간 URL(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"순차 범위
순차 다운로드(병렬이 서버를 압도하거나 레이트 리밋을 위반할 때)에는 bash에서 URL 을 루프로 돌리세요. 예의상 sleep을 추가합니다. -sf(silent + fail)는 HTTP 오류에서 curl이 0이 아닌 종료 코드를 돌려주게 해 루프가 조기 종료할 수 있습니다. 스크래핑/크롤링의 안전한 패턴입니다: 예의를 지키고, 지연을 넣고, 오류를 처리하세요.
# 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 & curl
GNU parallel은 xargs보다 강력합니다: 출력 순서를 보존하고, 진행 표시(--bar)를 보여주며, 인수를 더 유연하게 다룹니다. -j N이 동시성을 설정하고, ::::는 파일에서, :::는 커맨드라인에서 읽습니다. 병렬 요청에서 깔끔하고 정렬된 출력이 필요한 배치 API 테스트, 스크래핑, 벤치마크에 이상적입니다.
# 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.txt설정 파일
.curlrc 기본
~/.curlrc는 모든 curl 실행에 적용되는 기본 옵션을 담습니다. 앞의 -- 없이 긴 옵션 이름을 쓰세요. 한 줄에 하나의 옵션이며 값은 따옴표로 감쌀 수 있습니다. 흔한 설정(타임아웃, 재시도, User-Agent)을 스크립트와 대화형 사용에서 일관되게 유지합니다. 요청별로 덮어쓰려면 커맨드라인에서 옵션을 명시적으로 전달하세요.
# ~/.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 above설정 파일 위치
curl은 기본적으로 ~/.curlrc(또는 $CURL_HOME/.curlrc)를 읽습니다. -K(--config)는 특정 파일을 가리키고, -K -는 stdin에서 읽습니다. -q(--disable)는 설정 파일을 완전히 건너뜁니다 — 기본 옵션이 특정 요청을 망가뜨릴 때 유용합니다. CURL_HOME은 이식성 있는 환경을 위해 검색 디렉터리를 옮깁니다.
# 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 config-K로 설정 로드
-K는 파일에서 옵션을 로드합니다 — 환경별 설정(개발 vs 운영 토큰, 타임아웃, 헤더)에 완벽합니다. 설정 파일(chmod 600)에 시크릿을 저장하면 셸 히스토리와 ps에 노출되지 않습니다. 여러 -K 파일은 순서대로 처리되며 뒤의 파일이 앞의 것을 덮어쓰므로, 기본 설정 + 환경별 오버라이드 구성에 유용합니다.
# 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.com추천 기본값
탄탄한 ~/.curlrc는 모든 curl 실행을 더 안전하고 일관되게 만듭니다: 타임아웃은 멈춤을 막고, 재시도는 일시적 실패를 처리하며, --compressed는 gzip을 투명하게 처리하고, 다듬은 User-Agent는 핑거프린팅을 줄입니다. write-out 줄은 모든 요청의 타이밍과 상태를 기록합니다 — 빠른 성능 점검에 매우 유용합니다.
# ~/.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"다중 설정
설정을 계층 파일(base, auth, api, environment)로 나누면 모듈성과 보안이 유지됩니다. 여러 -K flag로 순서대로 처리하세요 — 뒤의 파일이 앞의 것을 덮어씁니다. 시크릿은 버전 관리 밖의 600 권한 파일에 두세요. 스택을 로드하는 래퍼 스크립트를 만들면 모든 기본값이 적용된 'mycurl'을 부를 수 있습니다.
# 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.com고급 기법
연결 재사용
단일 curl 실행 안에서는 같은 호스트로의 여러 URL에 TCP 연결이 재사용됩니다(HTTP keep-alive) — TLS 핸드셰이크 오버헤드를 아낍니다. --no-keepalive가 이를 비활성화합니다. --max-connects는 다중 URL 가져오기의 동시 연결 수를 제한합니다. 별개의 curl 호출 간에는 연결 재사용이 없으므로, 그런 경우 httpie 같은 지속 클라이언트나 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 & HTTP/3
HTTP/2는 하나의 연결 위에서 요청을 멀티플렉싱하고, HTTP/3는 UDP 위의 QUIC으로 HOL 블로킹(head-of-line blocking)을 없앱니다. --http2는 TLS 위에서 ALPN으로 협상하고, --http2-prior-knowledge는 협상을 건너뜁니다(클리어텍스트 h2c용). --http3는 특별한 curl 빌드가 필요합니다. 실제 사용된 버전은 %{http_version}으로 확인하세요. 대부분의 모던 CDN은 기본으로 h2를 지원합니다.
# 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.com조건부 요청
조건부 요청은 대역폭을 아낍니다: 리소스가 바뀌지 않았으면 서버가 304 Not Modified(본문 없음)를 돌려줍니다. -z(--time-cond)는 날짜나 로컬 파일의 mtime으로 If-Modified-Since를 설정합니다. ETag 기반 캐싱에는 If-None-Match를 직접 설정하세요. If-Unmodified-Since는 낙관적 동시성을 가능하게 합니다 — 다른 누군가 리소스를 수정했다면 PUT이 실패합니다.
# 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/data인터페이스 & DNS
--interface는 네트워크 카드나 IP에 바인딩합니다 — 멀티홈 머신에서 유용합니다. --resolve는 DNS를 우회해 호스트를 IP에 고정하며, 로드밸런서 뒤의 백엔드 테스트에 좋습니다. --doh-url은 DNS-over-HTTPS를 씁니다(프라이버시). -4/-6은 IP 계열을 강제합니다. Happy Eyeballs(기본값)는 IPv6 블랙홀 지연을 피하려고 IPv4와 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.comRange 요청 & 부분 전송
Range 요청(-r)은 파일의 일부를 가져와 206 Partial Content를 돌려줍니다. 사용 사례: 큰 파일 미리보기, 병렬 다중 연결 다운로드(범위로 나눠 동시에 가져와 이어 붙이기), 중단된 전송 재개(-C -). 서버가 Accept-Ranges: bytes를 알려야 합니다. 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 HTTP종료 코드
curl의 종료 코드는 실패 유형을 구분합니다: 6(DNS), 7(연결), 22(HTTP 오류, -f일 때만), 28(타임아웃), 35(TLS), 60(인증서). 이를 활용하면 적절히 재시도하는 견고한 스크립트를 만들 수 있습니다(예: 28에서는 재시도, 6에서는 빠른 실패). --fail-with-body는 4xx/5xx에서도 응답 본문을 돌려주므로 -f보다 API 오류 디버깅이 훨씬 쉽습니다.
# 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.com관련 curl 스니펫
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?