Simple JSON parsing from Bash using Python

Have a Bash command you like to use a lot but need to parse some JSON data from another script? Here’s a quick inline Python command you might find helpful:

COUNT=`|python -c "import json; import sys;
  data=json.load(sys.stdin); print data['count']"`

Just substitute the name of your other shell script ( and the JSON index (count) as appropriate and you’re all set!

Oh, and of course, join the 2 preformatted lines above also – these are just split because by WordPress theme was truncating the single-line version.

Variable manipulation from within a Bash subshell

Consider a shell script that counts the number of lines in a file. There are a number of ways to do this and I initially chose the following method:

cat /tmp/file.txt | while read LINE;
echo "Number of lines was $NUMLINES"

However, using this approach the value of NUMLINES was always zero after the while loop has ended, even though when I printed out its value inside the while loop it appeared to be incrementing just fine.

The problem turned out to be the use of the pipe at the beginning of the the while loop. This causes a new sub-shell to be created, which in turn creates a new local version of the NUMLINES. Thus, the original copy of the NUMLINES variable (outside the while loop) is never actually changed. Here is one solution to this that eliminates the use of the pipe (i.e. replace the piping of the file in the while with a redirection from the file at the end of the while statement):

while read LINE;
done < /tmp/file.txt
echo "Number of lines was $NUMLINES"

This worked for me!

Linux /etc/bash.bashrc versus /etc/profile

The most common place that people add system-wide environment variables on Linux is in /etc/profile. However, this requires that you log out and back in again (or start another session) for these changes to take effect. Whilst this is acceptable practise for most Linux desktop developers, I find it a little tedious when working from the Linux command-line.

So, after a little probing, I discovered that you can also make system-wide changes in /etc/bash.bashrc file but can use these immediately by simply invoking a new bash session (by typing bash at the same command prompt).

Of course if you have desktop applications that require the new settings then you will still have to log out and back in again as before but, if like me, you work a lot from the command-line, then you have the added benefit of being able to use the new settings immediately.