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

查看:282
本文介绍了如何从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=ok.

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=$(echo "$QUERY_STRING" | sed -n 's/^.*b=\([^&]*\).*$/\1/p' | sed "s/%20/ /g")

会将$ b设置为在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?

也许我只会使用某种for循环,但是如果脚本足够聪明以自动检测每个参数并构建看起来像这样的数组会更好:

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

我该如何编写代码来做到这一点?

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

在具有关联数组的Bash 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

这将为您提供:

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

您可以直接访问以下内容:

You can access these directly:

echo $var_a

或间接:

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

如果可能的话,最好避免间接访问,因为它会使代码混乱并且成为源代码错误.

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天全站免登陆