Mastering jq: Bash tricks
In this tutorial, we’ll demonstrate jq features that help us code bash faster.
Each section will present a feature in the following order
A brief description of the feature
A simple example you can copy and paste into your terminal
A sophisticated real world example of using the feature
A detailed explanation of the feature
Protips about how to use the feature effectively
The tutorial assumes basic knowledge of jq and bash.
Bash exit code
The -e flag changes jq’s bash exit code to depend on the program’s output.
Examples
Simple
# succeeds (exit code 0)
echo '{"f": [0] }' | jq -e '.f | length == 1'
# fails (exit code 1)
echo '{"f": [] }' | jq -e '.f | length == 1'
Primitive log monitoring
# This notifies a specified user through a command "notify-user" if app.log has an error log line in the past 10 lines.
while true; do
sleep 1
tail app.log |
jq -se 'map(select(.level == "ERROR")) != []' > /dev/null && notify-user adams "app.log has errors, please investigate" && break
done