如何使用 curl artifactory AQL 查询进行 bash 变量替换

How to do bash variable replacement with curl artifactory AQL query

我希望能够在以下对 Artifactory 查询语言 api (AQL)

的查询中使用 bash 变量替换

在shell中,命令是这样的:

$ curl -H 'content-type: text/plain' -H 'X-Api-Key: APIKEYGOESHERE' -X POST https://foo.jfrog.io/foo/api/search/aql -d '
> items.find({
>         "repo":{"$eq":"foo-docker"},
>         "path":{"$match":"REPONAME/*"}
> })
> .sort({
>         "$desc":["created"]
> }
> ).limit(1)'

{
"results" : [ {
  "repo" : "docker-local",
  "path" : "REPONAME/0.0.1-dev.54621",
  "name" : "manifest.json",
  "type" : "file",
  "size" : 3470,
  "created" : "2019-12-31T11:09:38.106Z",
  "created_by" : "automation",
  "modified" : "2019-12-31T11:09:37.940Z",
  "modified_by" : "automation",
  "updated" : "2019-12-31T11:09:38.107Z"
} ],
"range" : {
  "start_pos" : 0,
  "end_pos" : 1,
  "total" : 1,
  "limit" : 1
}

然而,事实证明,将此 curl 命令放入 bash 变量并进行替换很困难

这是我到目前为止尝试过的方法,没有成功

#!/bin/bash
# This script can find the most recent version of a docker image in artifactory

if [ $# -ne 2 ]; then
    echo "Usage: [=12=] apikey repo-path-name"
    exit 1
fi

apikey=
echo "apikey: $apikey"
repopath=
echo "repopath: $repopath"

output=`curl -H 'content-type: text/plain' -H "X-Api-Key: $apikey" -X POST https://foo.jfrog.io/foo/api/search/aql -d 'items.find({
        "repo":{"$eq":"foo-docker"},
        "path":{"$match":"$repopath/*"}
})
.sort({
        "$desc":["created"]
}
).limit(1)'`

echo $output

它几乎可以工作,除了 $repopath 变量没有被替换到调用中。

变量没有扩展,因为它在单引号内(从 items.find 之前开始)。你应该暂时从单引号切换到双引号来做扩展,像这样:

#!/bin/bash
# This script can find the most recent version of a docker image in artifactory

if [ $# -ne 2 ]; then
    echo "Usage: [=10=] apikey repo-path-name"
    exit 1
fi

apikey=
echo "apikey: $apikey"
repopath=
echo "repopath: $repopath"

output=`curl -H 'content-type: text/plain' -H "X-Api-Key: $apikey" -X POST https://foo.jfrog.io/foo/api/search/aql -d 'items.find({
        "repo":{"$eq":"foo-docker"},
        "path":{"$match":"'"$repopath"'/*"}
})
.sort({
        "$desc":["created"]
}
).limit(1)'`

echo $output