Skip to content

Instantly share code, notes, and snippets.

@westfly
Last active May 10, 2023 02:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westfly/ed7e25ee4353751d94132f92837a7074 to your computer and use it in GitHub Desktop.
Save westfly/ed7e25ee4353751d94132f92837a7074 to your computer and use it in GitHub Desktop.
urlencode for shell
function urlencode() {
local data
if [[ $# != 1 ]]; then
echo "Usage: $0 string-to-urlencode"
return 1
fi
data="$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode "$1" "")"
if [[ $? == 0 ]]; then
echo "${data##/?}"
fi
return 0
}
@snowman
Copy link

snowman commented Sep 29, 2020

do NOT use the above snippet, it's not reliable.

@androidfans
Copy link

echo $1 | perl -MURI::Escape -lne 'print uri_escape($_)'

@liuzhizhiyi
Copy link

just use
curl --data-urlencode 'key=val' URL
is OK. do not use other useless scripts.

@Exadra37
Copy link

Exadra37 commented Jul 27, 2022

A bash script that works based on the one in this gist:

#!/bin/sh

set -eu

# SAVE THIS FILE AND GIVE IT EXECUTABLE PERMISSIONS
# Then execute it like this: ./urlencode.sh https://apibaas.io
# Output: https%3A%2F%2Fapibaas.io

Main() {

  local input=${1? Missing the data to URL encode...}

  local data="$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode "${input}" "")"

  echo "${data##/?}"
}


Main "${@}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment