0

我正在使用破折号,我需要创建将解析查询字符串并将每个值保存到变量的 CGI 脚本

OLDIFS=$IFS                
// use & as delimeter
IFS='&'

//this will loop the queryString variable               
for line in $queryString;  
do     
//check if the key = action, if the condition was satisfied it will save the line to a variable..
//if the key is equal to type etc. etc.                                                 
        echo "{$line,1}"                                                   
        if[{$line,0:7}="action="]
                then
                cgi_action={$line:8}
        elif[{$line:0:5}="type="]
                then
                cgi_type={$line:6}                                  
        fi                       
done                             
IFS=$OLDIFS        

我确定我在获取行(或字符串)的子字符串时出错,但请让我们关注我在 for 循环中放置 if 语句时遇到的错误。在破折号 shell 脚本中,在 for 循环中编写 if 条件的正确方法是什么。

附加信息,我使用的是 ubuntu 14.04,

4

1 回答 1

1

首先,shell 脚本中的注释是#, not //,这意味着您的脚本在尝试解析时会混淆破折号。

其次,您必须在 if 条件中的所有标记周围放置空格 - 这实际上是您编写它的方式的语法错误,例如将操作测试更改为:

if [ {$line,0:7} = "action=" ]

第三,dash不支持子串提取,即使支持,正确的格式是:

${variable:start}
${variable:start:nchars}

如果您想使用子字符串提取,那么您应该使用bash而不是dash.

第三,您在值提取的索引中遇到了一个错误 - 您正在删除字符串中的第一个字符。例如,您从 offset 检查值0的长度,然后从 index 中获取所有内容,这比您应该使用的要大一。5type=6

你的代码最好是这样的:

OLDIFS=$IFS
# use & as delimeter
IFS='&'

#this will loop the queryString variable
for line in $queryString; do
    #check if the key = action, if the condition was satisfied it will save the line to a variable..
    #if the key is equal to type etc. etc.

    echo "${line:1}"
    if [ ${line:0:7} = "action=" ]; then
        cgi_action=${line:7}
    elif [ ${line:0:5} = "type=" ]; then
        cgi_type=${line:5}
    fi
done
IFS=$OLDIFS

并不是说我会推荐使用 shell 来编写 CGI 脚本

于 2015-01-09T10:46:13.860 回答