Search code examples
bashshellmakefileterminal

Bash script to print contents of json file


I am very new to bash scripting and am trying to add a bash script in my Makefile. I have a errors.json file. How do I write a bash script in my Makefile that checks if the file has any contents. If it is not empty then echo the contents of the error.json file else finish. Here is the psuedocode below:

if [[ !error.json.isEmpty() ]]; then \
     cat error.json; \
     delete the error.json; \
else \
     delete the error.json;
fi

Solution

  • First of all, not all distros have /bin/sh set up as a symlink to run bash. To force Bash-compatible syntax in your makefile, you must put this line near the top:

    SHELL := /bin/bash
    

    Short answer: you don't have to check if the file is empty or doesn't exist. Just silence the error if the file doesn't exist:

    display-errors:
        @cat error.json 2>/dev/null ;\
        rm -f error.json
    

    If you wanted to get fancier about it:

    display-errors:
        @if [[ -s error.json ]]; then \
            cat error.json ;\
        fi ;\
        rm -f error.json
    

    Examples here are written as makefile targets. The weird line ending ;\ is there because Make targets assume every line is going to be a separate command. If you specify make -j4 these lines may even run in parallel! Adding \ to the end of a line is a signal to Make that the line continues below. A ; is added to tell it to separate the commands even though they're executing from the same line.

    @ is simply to prevent Make from echoing the command as it executes.

    Also, the tab characters in this answer are intentional; Make requires them.

    From bash(1) documentation for [[ .. ]] or the test built-in:

    -s file

    True if file exists and has a size greater than zero.