简体   繁体   English

如何在json文件中传递bash变量值

[英]How to pass bash variable value in json file

Add bash variables value to json file将 bash 变量值添加到 json 文件

I am trying to get latest zip file from nexus using below curl command.我正在尝试使用以下 curl 命令从 nexus 获取最新的 zip 文件。

Ouput of curl comes like this : 1.0.0.0-20190205.195251-396 curl 的输出是这样的:1.0.0.0-20190205.195251-396

In the json field i need this value(1.0.0.0-20190205.195251-396) to be updated like this: developer-service-1.0.0.0-20190205.195251-396.zip在 json 字段中,我需要这个值(1.0.0.0-20190205.195251-396)像这样更新:developer-service-1.0.0.0-20190205.195251-396.zip

ERROR: [2019-02-06T16:19:17-08:00] WARN: remote_file[/var/chef/cache/developer-service-.zip] cannot be downloaded from https://nexus.gnc.net/nexus/content/repositories/CO-Snapshots/com/GNC/platform/developer/developer-service/1.0.9.9-SNAPSHOT/developer-service-.zip : 404 "Not Found"错误:[2019-02-06T16:19:17-08:00] 警告:无法从https://nexus.gnc.net/nexus下载 remote_file[/var/chef/cache/developer-service-.zip] /content/repositories/CO-Snapshots/com/GNC/platform/developer/developer-service/1.0.9.9-SNAPSHOT/developer-service-.zip:404 “未找到”

#!/bin/bash
latest=`curl -s http://nexus.gnc.net/nexus/content/repositories/CO-Snapshots/com/gnc/platform/developer/developer-service/1.0.9.9-SNAPSHOT/maven-metadata.xml | grep -i value | head -1 | cut -d ">" -f 2 | cut -d "<" -f 1`

echo $latest

sudo bash -c 'cat << EOF > /etc/chef/deploy_service.json
{
  "portal" : {
    "nexus_snapshot_version":"developer-service-${latest}.zip"
    }
}
EOF'

The problem is that when you use "${latest}", it's inside single-quotes, and hence not treated as a variable reference, just some literal text;问题是当你使用 "${latest}" 时,它在单引号内,因此不被视为变量引用,只是一些文字; it's passed to a subshell (the bash -c , and that will parse it as a variable reference and replace it with the value of the variable latest , but that variable is only defined in the parent shell, not in the subshell. You could probably export the variable (so it gets inherited by subprocesses) and use sudo -E to prevent sudo from cleaning the environment (hence removing the variable)... But this whole thing is an overcomplicated mess; there's a much simpler way, using the standard sudo tee trick :它传递给子shell(在bash -c将解析它作为一个变量引用,并与变量的值替换它latest ,但该变量仅在父shell定义,而不是在子shell。你很可能export变量(因此它被子进程继承)并使用sudo -E来防止sudo清理环境(因此删除变量)......但这整个事情过于复杂;有一种更简单的方法,使用标准sudo tee技巧

sudo tee ./deploy_service.json >/dev/null <<EOF
{
  "portal" : {
    "nexus_snapshot_version":"developer-service-${latest}.zip"
    }
}
EOF

This way there's not single-quoted string, no subshell, etc. The variable reference is now just in a plain here-document (that's interpreted by the shell that knows $latest ), and gets expanded normally.这样就没有单引号字符串,没有子shell等。变量引用现在只是在一个普通的here-document中(由知道$latest的shell解释),并且正常展开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM