How to resolve the algorithm URL decoding step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm URL decoding step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm URL decoding step by step in the UNIX Shell programming language

Source code in the unix programming language

urldecode() { local u="${1//+/ }"; printf '%b' "${u//%/\\x}"; }


urldecode http%3A%2F%2Ffoo%20bar%2F
http://foo bar/

urldecode google.com/search?q=%60Abdu%27l-Bah%C3%A1
google.com/search?q=`Abdu'l-Bahároot@


function urldecode
{
        typeset encoded=$1 decoded= rest= c= c1= c2=
        typeset rest2= bug='rest2=${rest}'

        if [[ -z ${BASH_VERSION:-} ]]; then
                typeset -i16 hex=0; typeset -i8 oct=0

                # bug /usr/bin/sh HP-UX 11.00
                typeset _encoded='xyz%26xyz'
                rest="${_encoded#?}"
                c="${_encoded%%${rest}}"
                if (( ${#c} != 1 )); then
                        typeset qm='????????????????????????????????????????????????????????????????????????'
                        typeset bug='(( ${#rest} > 0 )) && typeset -L${#rest} rest2="${qm}" || rest2=${rest}'
                fi
        fi

	rest="${encoded#?}"
	eval ${bug}
	c="${encoded%%${rest2}}"
	encoded="${rest}"

	while [[ -n ${c} ]]; do
		if [[ ${c} = '%' ]]; then
			rest="${encoded#?}"
			eval ${bug}
			c1="${encoded%%${rest2}}"
			encoded="${rest}"

			rest="${encoded#?}"
			eval ${bug}
			c2="${encoded%%${rest2}}"
			encoded="${rest}"

			if [[ -z ${c1} || -z ${c2} ]]; then
				c="%${c1}${c2}"
				echo "WARNING: invalid % encoding: ${c}" >&2
			elif [[ -n ${BASH_VERSION:-} ]]; then
				c="\\x${c1}${c2}"
				c=$(\echo -e "${c}")
			else
				hex="16#${c1}${c2}"; oct=hex
				c="\\0${oct#8\#}"
				c=$(print -- "${c}")
			fi
		elif [[ ${c} = '+' ]]; then
			c=' '
		fi

		decoded="${decoded}${c}"

		rest="${encoded#?}"
		eval ${bug}
		c="${encoded%%${rest2}}"
		encoded="${rest}"
	done

	if [[ -n ${BASH_VERSION:-} ]]; then
		\echo -E "${decoded}"
	else
		print -r -- "${decoded}"
	fi
}


  

You may also check:How to resolve the algorithm Van der Corput sequence step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Grayscale image step by step in the Lua programming language
You may also check:How to resolve the algorithm Count in octal step by step in the COBOL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Patience sort step by step in the Nim programming language
You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the Picat programming language