How to read query string from shell script?

Hi,

I am new this shell scripting. I have one html page which is executing shell script. That web form is passing some query strings to the script. Now how can I read query string in shell script and parse it in variables.

I tried with below shell script but its not working.

#!/bin/sh

saveIFS=$IFS
IFS='=&'
param=($QUERY_STRING)
IFS=$saveIFS

echo "$param[2]";

# ./test.cgi name=jdp
./test.cgi: line 5: syntax error: "(" unexpected

Appreciate your help in resolving this?

Thanks,
Jdp

What OS are you using? If Solaris, sh does not support arrays, if AIX sh is a link to ksh which may not support that array syntax - use set -A

In addition, the syntax of line 8 is wrong.

echo ${param[2]}

Thanks Scott for your reply,

I am using linux running on device. I tried your suggestion but it is throwing error for declare.

Which Linux (i.e. Fedora, Debian, etc.), on what "device"? Try pointing the "shebang" on line one to /bin/bash, if it exists, or say what /bin/sh is pointing to.

Thanks Scott,

The device is having linux OS and running a shttpd web server. I checked the /bin directory, It has sh only and I didn't find bash. I have never written shell scripts so looking for a script which can read GET/POST data using shell scripts.

Clearly, the problem is with the array (param=($QUERY_STRING)). Your shell doesn't support them, or doesn't support them in that format. You'll need to find an alternative way of getting the values.

i.e.

$ cat myScript
QUERY_STRING="a=1&b=2&c=3&d=4&e=5"
IFS='=&'
set -- $QUERY_STRING

echo $3 is $4
echo $9 is ${10}

$ ./myScript
b is 2
e is 5

# or

$ cat myScript
QUERY_STRING="a=1&b=2&c=3&d=4&e=5"
IFS='&'
set -- $QUERY_STRING
echo ${2%=*} is ${2#*=}

$ ./myScript
b is 2

You didn't answer either of my questions: Which Linux are you using, and what is a "device".

1 Like

Thank Scott for your code. I really appreciate.

I did some googling and managed to get the data using POST request from HTML using JavaScript. Posting the code in case someone newbie like me need to achieve the same,

#!/bin/sh

if [ "$REQUEST_METHOD" = "POST" ]; then
  if [ "$CONTENT_LENGTH" -gt 0 ]; then
      read -n $CONTENT_LENGTH POST_DATA <&0
  fi
fi

#echo "$POST_DATA" > data.bin
IFS='=&'
set -- $POST_DATA

#2- Value1
#4- Value2
#6- Value3
#8- Value4

echo $2 $4 $6 $8

echo "Content-type: text/html"
echo ""
echo "<html><head><title>Saved</title></head><body>"
echo "Data received: $POST_DATA"
echo "</body></html>"