-2

I am trying to parse json result from aws result, but I getting error or null when I am using $ip, when I am using specific IP it work. something wrong when I am using tne variable inside the jq command

#!/bin/bash

aws ec2 describe-addresses --region eu-west-1 > 1.txt
ipList=( "52.16.121.238" "52.17.250.188" )

for ip in "${ipList[@]}";
do
    echo $ip
    cat 1.txt | jq '.Addresses | .[] | select (.PublicIp==$ip) |    .InstanceId'
    #echo $result
done

Please advise.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
cfircoo
  • 417
  • 2
  • 8
  • 23
  • Take a look at: [Difference between single and double quotes in bash](http://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – Cyrus Jun 28 '15 at 19:19
  • Nope still not working – cfircoo Jun 28 '15 at 19:31
  • edit your question with the specifics of "stlll not working". Its difficult to guess what error messages you might be getting, given the unkown content of `1.txt`. Also, I assume you are using good practice and working with just the problem line of `cat 1.txt | jq ...` and that is why `echo result` below is commented out AND that you have no assignment shown like `result=$(...something...)` . Good luck. – shellter Jun 28 '15 at 20:26
  • @cfircoo: Interrupt the single quotes with double quotes: `cat 1.txt | jq '.Addresses | .[] | select (.PublicIp=='"$ip"') | .InstanceId'` – Cyrus Jun 28 '15 at 20:42
  • You might also want to consider using the --query option, for example: aws ec2 describe-addresses --query "Addresses[*].PublicIp" --output text – jarmod Jun 29 '15 at 00:05

2 Answers2

5

You're using single quotes around your jq program, which is causing the shell variable to not be interpolated. Furthermore, even if it were, you would still need to add string quoting around the variable interpolation to make jq interpret it as a string literal. Since doing shell variable interpolation into jq programs is hard and error-prone, jq provides a command-line argument to this effect, --arg, intended to lift shell variables into jq variables. Your jq invocation would therefore look like this:

jq --arg ip "$ip" '.Addresses[] | select(.PublicIp == $ip) | .InstanceId'

  • 1
    Also, `jq` reads a file name argument, so the `cat` is [useless as usual](http://www.iki.fi/era/unix/award.html). – tripleee Jun 30 '15 at 03:39
-1

Thanks for your help. the right format is:

cat 1.txt | jq ".Addresses | .[] | select(.PublicIp==\"$ip\") | .InstanceId"
cfircoo
  • 417
  • 2
  • 8
  • 23
  • That's a _bad_ idea. You should try to keep your filter string constant. If you're going to parameterize it, use the `--arg` option. – Jeff Mercado Jun 30 '15 at 17:38