Skip to content

Instantly share code, notes, and snippets.

@pablochacin
Last active January 27, 2023 01:32
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pablochacin/8016575 to your computer and use it in GitHub Desktop.
Save pablochacin/8016575 to your computer and use it in GitHub Desktop.
A one liner to parse a http query string in bash
#
# the following one liner creates a shell variable from every parameter in a
# the query string in the variable QUERY, of the form p1=v1&p2=v2,... and sets it to
# the corresponding value so that parameters can be accessed by its name $p1, $p2, ...
#
for p in ${QUERY//&/ };do kvp=( ${p/=/ } ); k=${kvp[0]};v=${kvp[1]};eval $k=$v;done
@mstyles
Copy link

mstyles commented Apr 30, 2015

👍

@Shulyaka
Copy link

Shulyaka commented Sep 24, 2019

What about http://localhost/cgi-bin/script.sh?reboot;a=a ?

@easyhorpak
Copy link

easyhorpak commented Oct 19, 2021

try this

protect_shell(){

QUERY_STRING=$(echo "${QUERY_STRING}" | sed 's/;//g')

if [ "${QUERY_STRING}" ]; then

	export IFS="&"
	for cmd in ${QUERY_STRING}; do
	
		 if [ "$(echo $cmd | grep '=')" ]; then
		 	key=$(echo $cmd | awk -F '=' '{print $1}')
		 	value=$(echo $cmd | awk -F '=' '{print $2}')
		 	eval $key=$value
		 fi
		 
	done

fi

QUERY_STRING=""

}

@jasonk
Copy link

jasonk commented Jan 27, 2023

If you are just going to assume that nothing is URL encoded and use eval to set variables, then all you really need is:

eval "${QUERY_STRING//&/$'\n'}"

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