0

I want to create a shell script function that runs this:

docker inspect 5914ba2819d6 | jq '.[0].NetworkSettings.Networks["foo"].IPAddress'

I'm trying to get the function to run like:

getcontainerip 5914ba2819d6 foo

I've edited .bash_profile to have many permutations like this:

getcontainerip() {
   docker inspect "$1" | jq '.[0].NetworkSettings.Networks["$2"].IPAddress'
}

No matter what, the literal double quotes never get added surrounding the second parameter. The output will either be blank (because the double quotes aren't there), or a syntax error:

jq: error: syntax error, unexpected '$' (Unix shell quoting issues?)

How do I get the literal double quotes to surround the second parameter? Thanks.

kcpkrad
  • 3
  • 1
  • With `jq` specifically you should use `--arg name value` or `--argjson name json` to pass variables to it. These options will handle escaping special characters correctly. If you inject `$2` directly into the script it's likely to fail if `$2` contains quotes, backslashes, etc. – John Kugelman Dec 02 '21 at 05:10

1 Answers1

0

Try this:

getcontainerip() {
   docker inspect "$1" | jq '.[0].NetworkSettings.Networks["'$2'"].IPAddress'
}

The outer '' have the effect that $2 is not replaced with the second parameter but rather passed literally to jq. That's why you need to close the ''s temporarily to let the shell expand $2.

D-FENS
  • 1,438
  • 8
  • 21