如何从一个bash CGI脚本解析$ QUERY_STRING [英] How to parse $QUERY_STRING from a bash CGI script

查看:392
本文介绍了如何从一个bash CGI脚本解析$ QUERY_STRING的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在CGI正在使用bash脚本。该CGI通过读取URL一切后?设置$ QUERY_STRING环境变量。例如, http://example.com?a=123&b=456&c=ok QUERY_STRING = A = 123和b = 456安培; C =确定

I have a bash script that is being used in a CGI. The CGI sets the $QUERY_STRING environment variable by reading everything after the ? in the URL. For example, http://example.com?a=123&b=456&c=ok sets QUERY_STRING=a=123&b=456&c=ok.

某处我发现下面的丑陋:

Somewhere I found the following ugliness:

B = $(回声$ QUERY_STRING| sed的-n的/^.* B = \\([^&安培]。* \\)* $ / \\ 1 / p'| SEDS / 20%/ / G)

这将设置$ B到任何在$ QUERY_STRING被发现的 B 。然而,我的脚本已成长为拥有十多个输入参数。是否有更简单的方法来自动在$ QUERY_STRING参数转换成可用的环境变量被Bash?

which will set $b to whatever was found in $QUERY_STRING for b. However, my script has grown to have over ten input parameters. Is there an easier way to automatically convert the parameters in $QUERY_STRING into environment variables usable by bash?

也许我会只使用一个某种类型的循环,但它会是更好的,如果剧本足够聪明的自动检测各项参数,也许建立一个数组,看起来是这样的:

Maybe I'll just use a for loop of some sort, but it'd be even better if the script was smart enough to automatically detect each parameter and maybe build an array that looks something like this:


${parm[a]}=123
${parm[b]}=456
${parm[c]}=ok

我怎么能写code这样做呢?

How could I write code to do that?

推荐答案

试试这个:

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

现在你有这样的:

parm[0]=a
parm[1]=123
parm[2]=b
parm[3]=456
parm[4]=c
parm[5]=ok

在猛砸4,具有关联数组,你可以这样做(使用上面创建的数组):

In Bash 4, which has associative arrays, you can do this (using the array created above):

declare -A array
for ((i=0; i<${#parm[@]}; i+=2))
do
    array[${parm[i]}]=${parm[i+1]}
done

这将给你这样的:

which will give you this:

array[a]=123
array[b]=456
array[c]=ok

编辑:

要在Bash中2和更高版本(使用上面创建的 PARM 数组)使用间接

To use indirection in Bash 2 and later (using the parm array created above):

for ((i=0; i<${#parm[@]}; i+=2))
do
    declare var_${parm[i]}=${parm[i+1]}
done

然后,你将有:

var_a=123
var_b=456
var_c=ok

您可以直接访问这些:

echo $var_a

或间接的:

for p in a b c
do
    name="var$p"
    echo ${!name}
done

如果可能的话,最好是避免间接,因为它可以使code混乱,是bug的来源

If possible, it's better to avoid indirection since it can make code messy and be a source of bugs.

这篇关于如何从一个bash CGI脚本解析$ QUERY_STRING的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆