Home > OS >  How to get a command variable inside another command variable?
How to get a command variable inside another command variable?

Time:10-25

Example here:

gitrepo=$(jq -r '.gitrepo' 0.json)
releasetag=$(curl --silent ""https://api.github.com/repos/\"$gitrepo\""/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"] )".*/\1/')
echo "$releasetag"

Used \" to escape characters.

0.json:

{
        "type": "github-releases",
        "gitrepo": "ipfs/go-ipfs"
}

How to put $gitrepo to work inside $releasetag? Thanks in advance!

CodePudding user response:

Bash variables expand inside quoted " strings.

gitrepo="$(jq -r '.gitrepo' 0.json)"
releasetag="$(
  curl --silent "https://api.github.com/repos/$gitrepo/releases/latest" \
  | grep '"tag_name":' | sed -E 's/.*"([^"] )".*/\1/'
)"
echo "$releasetag"

Btw, as you are using jq to extract .gitrepo from 0.json, you could also use it in the exact same way to extract .tag_name from curl's output (instead of using grep and sed) like so:

gitrepo="$(jq -r '.gitrepo' 0.json)"
releasetag="$(
  curl --silent "https://api.github.com/repos/$gitrepo/releases/latest" \
  | jq -r '.tag_name'
)"
echo "$releasetag"

And to simplify it even further (depending on your use case), just write:

curl --silent "https://api.github.com/repos/$(jq -r '.gitrepo' 0.json)/releases/latest" \
| jq -r '.tag_name'
  • Related