Urlencode Data for the curl Command in Bash

Dr. Muhammad Abdullah Feb 02, 2024
Urlencode Data for the curl Command in Bash

The curl is a Linux command-line utility that transfers data from one machine to another. It can work with multiple protocols, including HTTP, DICT, FILE, FTP, FTPS, IMAP, IMAPS, POP3, etc.

This article will teach how we can urlencode data for the curl command in bash. Let’s start with the syntax of the curl command.

the curl Command in Bash

The curl command’s basic syntax is as follows:

curl [URL] [option]

Example:

curl http://example.com

This command shows the content of http://example.com on the Linux terminal.

curl Command Options

We can use multiple options with the curl command. Generally, options are started with one dash (-) or two dashes (--). For example curl command with one option can be written as follow:

curl -L [URL]

A curl command with multiple options can be written as follow:

curl -ELb [URL]

Or

curl -E -L -b [URL]

curl -d or --data Option

The -d or --data option with the curl command is used to send data to the server as a POST request. For example:

curl -d "p1=v1&p2=v2" [URL]

Or

curl --data "p1=v1&p2=v2" [URL]

This command sends data to the given URL. For example, the value of parameter p1 is v1, and the value of parameter p2 is v2, which is sent to the server. These parameters are sent in pure binary format.

curl supports a different format for sending the data to the server. For example:

  1. --data-ascii works the same as the -d or --data option.
  2. --data-binary option is used to send POST data in actual format as specified in the command without processing.
  3. --data-urlencode option sends POST data to the server by performing URL-encoding.

URL-Encode Data From curl Command

curl with --data-urlencode is used to send data to the server by performing URL-encoding.

For example:

curl --data-urlencode "p1=v1" [URL]

The above command curls the URL and passes the parameter p1 value v1 in the URL-encoded form. This command URL-encode the value v1 and expects that the p1 is already in URL-encoded form.

We can use this curl option with curl 7.18.0 or higher. For example, to check the curl command version, we can use curl -V.

The curl command with the --data-urlencode option can be used in multiple formats. For example:

  1. curl --data-urlencode =content [URL]
    

    This command will URL-encode the content and send it in the POST. The = is not included in the data.

  2. curl --data-urlencode name@file [URL]
    

    This command will URL-encode the data from the given file and send it in the POST. The command assumes the name is already in URL-encoded form.

  3. curl --data-urlencode @file [URL]
    

    This command will URL-encode the data from the given file and send it in the POST.