在Bash中命令构建和字符串转义

 乐乐 发布于 2023-02-07 20:56

我正在尝试构建一个Bash脚本,该脚本将从命令行获取参数以及硬编码参数,并将它们传递给函数,该函数将构造对curl的调用并执行HTTP POST.不幸的是,当我尝试传递带有空格的字符串时,脚本会破坏字符串,最终调用curl无法按正确的顺序传递参数:

#!/bin/bash

API_URL="http://httpbin.org/"

docurl() {
    arg1=$1
    shift
    arg2=$1
    shift

    args=()
    while [ "$1" ]
    do
        arg_name="$1"
        shift
        arg_value="$1"
        shift

        args+=(-d $arg_name="$arg_value")
    done

    curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1=$arg1 -d arg2=$arg2 ${args[@]} ) 2>/dev/null
    echo "$curl_result"
}

docurl foo1 foo2 title "$1" body "$2"

脚本调用将是这样的:

test2.sh "Hello" "Body of the message"

脚本的输出是这样的:

{
  "form": {
    "body": "Body",
    "arg1": "foo1",
    "arg2": "foo2",
    "title": "Hello"
  },
  "headers": {
    "Host": "httpbin.org",
    "Connection": "close",
    "Content-Length": "41",
    "User-Agent": "curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3",
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "*/*"
  },
  "files": {},
  "data": "",
  "url": "http://httpbin.org/post",
  "args": {},
  "origin": "xxx.xxx.xxx.xxx",
  "json": null
}

如您所见,在form元素中,字段"body"和"title"已被截断.任何人都可以告诉我这里我做错了什么吗?

1 个回答
  • 使用更多的报价!

        args+=(-d "$arg_name"="$arg_value")
    

    和:

    curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1="$arg1" -d arg2="$arg2" "${args[@]}" ) 2>/dev/null
    

    2023-02-07 21:04 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有