URL Encode a String in Linux Shell
Published on

URL Encode a String in Linux Shell

Authors

Lets say you have a password that contains special characters and you want to use it in a URL. You need to encode the password so that it can be used in the URL. In this article, we will see how to URL encode a string in Linux shell. Below is the command to URL encode a string in Linux shell:

$(curl -Gso /dev/null -w %{url_effective} --data-urlencode "pass=$pass" "" | cut -d'=' -f 2)

Here pass is the string to be encoded. --data-urlencode is used to URL encode the string. curl is used to send the request to the URL. cut -d'=' -f 2 is used to extract the encoded string from the URL. The string pass= is removed from the URL and the encoded string is extracted.

For example, if you want to encode the string password@123, you can use the following command:

pass="password@123"
encoded_pass=$(curl -Gso /dev/null -w %{url_effective} --data-urlencode "pass=$pass" "" | cut -d'=' -f 2)
echo $encoded_pass

This will output the encoded string password%40123. You can use this encoded password in the URL. Let me give you a example of how to use this encoded password in the URL.

Assuem you have a website https://example.com, which uses basic authentication and you want to pass the username & password to URL. We can assume that the username is user and the password is password@123. Because we have special characters in the password, we need to encode it. @ is encoded as %40.

pass="password@123"
encoded_pass=$(curl -Gso /dev/null -w %{url_effective} --data-urlencode "pass=$pass" "" | cut -d'=' -f 2)
url="https://user:$encoded_pass@example.com"
echo $url

This will output the URL https://user::password%[email protected]. You can use this URL to access the website.