Passing bash variable to python command within a shell script
<p>Needing to extract two variables per line from a JSON file and use each of these 2 variables in separate follow up commands.</p>

<p>My script is so far:</p>

<pre><code>#!/bin/bash

VCTRL_OUT='/tmp/workingfile.json'

old_IFS=$IFS      # save the field separator
IFS=$'\n'     # new field separator, the end of line

for line in $(cat $VCTRL_OUT)
  do
    python -c 'import json,sys;obj=json.load($line);print obj["ip_range"]'
  done
</code></pre>

<p>The second to last line is wrong and need to know how to do this.</p>

<p>The following works:</p>

<pre><code>cat /tmp/workingfile.json | head -n +1 | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["ip_range"]';
</code></pre>

<p>But not sure how to do the same in the bash script for loop.</p>

<p>Python wouldn't be my first choice for this kind of one-liner, but you might try</p>

<pre><code>#!/bin/bash

VCTRL_OUT='/tmp/workingfile.json'

parse_json () {
    python -c $'import json,fileinput,operator\nfor line in fileinput.input(): print "%s %s"%operator.itemgetter("ip_range","description")(json.loads(line))' "$1"
}
while IFS= read -r ip_range description; do
   # do your thing with ip_range
done &lt; &lt;(parse_json "$VCTRL_OUT")
</code></pre>

<p>One alternative is to replace the Python bit with <code>jq</code>:</p>

<pre><code>while IFS= read -r ip_range description; do
  # ...
done &lt; &lt;( jq -rRc 'fromjson | .ip_range+" "+.description' "$VCTRL_OUT")
</code></pre>

<p>Another alternative is to replace the entire <code>bash</code> script with Python, although that may be easier said than done, depending on what the <code>bash</code> script is actually doing.</p>

python json bash