Avoiding Shell Quote Hell And Managing Interpolation in Nested Quotes:
We’ve all been there. I ran command x, and now I want to run it in the context of command y but I’m dealing with nested strings and it’s a pain. I use this method to quickly avoid all the shell nonsense and escaping. I like to keep my snippets terse, so comments will be inline.
# This creates a method that will read lines into a variable. There's probably a limitation on bash versions, so this may not work on older systems.
define(){ IFS='\n' read -r -d '' ${1} || true; }
# Given jq, a popular cli json manipulator lets select the animal dog
# {
# "animals": [
# {
# "animal": "dog"
# },
# {
# "animal": "cat"
# }
# ]
# }
ANIMAL=dog
define JQ_COMMAND <<EOF
jq -r '.animals[] | select( .animal | contains("$ANIMAL"))'
EOF
# Then, with the previous json object in my paste buffer, we'll simple eval this command
pbpaste | eval $JQ_COMMAND
# Output:
# {
# "animal": "dog"
# }
# This example is contrived, but jq has wonkey stuff going on with quoting and sub quoting because it has its own interpreter. Since we create a here doc, we can pre-interpolate variables and then execute the whole command in line.


