The simplest way to use curl
with a link (URL) is to retrieve the content of a web page, displaying the HTML in your terminal.
Here's a breakdown of how to use curl
with links, along with examples and explanations:
Basic Usage
The fundamental syntax for using curl
with a URL is:
curl [URL]
curl
: The command-line tool itself.[URL]
: The web address you want to access (e.g.,https://www.example.com
).
Example:
To retrieve the HTML content of https://www.example.com
, you would use the following command:
curl https://www.example.com
This command will output the HTML source code of the specified webpage directly to your terminal.
Understanding the GET Request
By default, curl
performs a GET request when you provide a URL. A GET request asks the server to retrieve the resource (e.g., the HTML page) located at that URL.
Example of saving the output to a file:
curl https://www.example.com -o example.html
This saves the output from the URL https://www.example.com
to a file named example.html
.
Beyond the Basics: More Complex Usage
While simply displaying the HTML is useful, curl
can do much more with links. Here are a few common scenarios:
-
Downloading Files: Use the
-O
(uppercase O) option to download a file and save it with the same name as on the server.curl -O https://example.com/image.jpg
-
Specifying the Output Filename: Use the
-o
(lowercase o) option to download a file and give it a specific name.curl -o myimage.jpg https://example.com/image.jpg
-
Using Different HTTP Methods: You can use the
-X
option to specify a different HTTP method, such as POST. This is typically used when submitting data to a web server.curl -X POST -d "name=John&age=30" https://example.com/submit
In this example,
-X POST
tellscurl
to make a POST request and-d "name=John&age=30"
sends the provided data. -
Setting Headers: Use the
-H
option to include custom headers in the request. This is frequently used for authentication or to specify the content type.curl -H "Authorization: Bearer YOUR_API_KEY" https://api.example.com/data
Summary
curl
provides a versatile way to interact with web servers using URLs. Its basic function is to retrieve the content at a given link using a GET request, which displays the data in your terminal. The options available with curl
allow you to specify HTTP methods, set headers, download files, and more.