简体   繁体   中英

How to pass bash variable value in json file

Add bash variables value to json file

I am trying to get latest zip file from nexus using below curl command.

Ouput of curl comes like this : 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

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"

#!/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; 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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