Skip to content

Bash snippets

Do the remainder or modulus of a number

expr 5 % 3

Update a json file with jq

Save the next snippet to a file, for example jqr and add it to your $PATH.

#!/bin/zsh

query="$1"
file=$2

temp_file="$(mktemp)"

# Update the content
jq "$query" $file > "$temp_file"

# Check if the file has changed
cmp -s "$file" "$temp_file"
if [[ $? -eq 0 ]] ; then
  /bin/rm "$temp_file"
else
  /bin/mv "$temp_file" "$file"
fi

Imagine you have the next json file:

{
  "property": true,
  "other_property": "value"
}

Then you can run:

jqr '.property = false' status.json

And then you'll have:

{
  "property": false,
  "other_property": "value"
}