urlencode using bash script with live demo – Code Example

Total
0
Shares

In this article we will provide you bash script code to urlencode. This code will percent encode the string like `encodeURIComponent()` function in javascript.

Code Example –

#!/bin/bash

encodeURIComponent() {
    local LC_ALL=C
    for (( i = 0; i < ${#1}; i++ )); do
        : "${1:i:1}"
        case "$_" in
            [a-zA-Z0-9.~_-])
                printf '%s' "$_"
            ;;

            *)
                printf '%%%02X' "'$_"
            ;;
        esac
    done
    printf '\n'
}

encodeURIComponent "https://akashmittal.com/code-example-urlencode-using-bash-script-with-live-demo/"

# Output
# https%3A%2F%2Fakashmittal.com%2Fcode-example-urlencode-using-bash-script-with-live-demo%2F

Not only urls, you can encode any string with this function.

Inspired from Dylan Araps

Live Demo

Open Live Demo