0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use curl in Bash: Simple Commands and Examples

Use the curl command in bash to transfer data from or to a server by specifying a URL. Basic usage is curl [options] URL, where options control the request type and output.
📐

Syntax

The basic syntax of curl in bash is:

  • curl [options] URL

Here, URL is the web address you want to access. Options modify the request, such as specifying HTTP methods, headers, or output format.

bash
curl [options] URL
💻

Example

This example fetches the homepage of example.com and shows the HTML content in the terminal.

bash
curl https://example.com
Output
<!doctype html>\n<html>\n<head>\n <title>Example Domain</title>\n\n <meta charset="utf-8" />\n <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n <style type="text/css">\n body {\n background-color: #f0f0f2;\n margin: 0;\n padding: 0;\n font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n }\n div {\n width: 600px;\n margin: 5em auto;\n padding: 2em;\n background-color: #fdfdff;\n border-radius: 0.5em;\n box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n }\n a:link, a:visited {\n color: #38488f;\n text-decoration: none;\n }\n @media (max-width: 700px) {\n div {\n margin: 0 auto;\n width: auto;\n }\n }\n </style>\n</head>\n\n<body>\n<div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p><a href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>
⚠️

Common Pitfalls

Common mistakes when using curl include:

  • Not using -L to follow redirects, so you get a redirect message instead of the final content.
  • Forgetting to use -o filename to save output to a file, causing large outputs to flood the terminal.
  • Not specifying HTTP method with -X when needed (e.g., POST requests).
bash
curl http://github.com

# This returns a redirect notice instead of the page content

curl -L http://github.com

# This follows redirects and shows the final page content
📊

Quick Reference

Here are some useful curl options:

OptionDescription
-LFollow redirects automatically
-o filenameSave output to a file named filename
-IFetch only HTTP headers
-X METHODSpecify HTTP method (GET, POST, PUT, DELETE)
-d dataSend data in POST request body
-H 'Header: value'Add custom HTTP header

Key Takeaways

Use curl [options] URL to fetch or send data from/to a server in bash.
Add -L to follow redirects and get the final content.
Use -o filename to save output instead of printing to terminal.
Specify HTTP methods with -X and send data with -d for POST requests.
Custom headers can be added with -H option.