bashloopsshell

How to loop each JSON files on bash script to know if content of the file in empty or not empty?


Here's my bash script on looping the JSON files to know if content of the file in empty or not empty. Tried to test this script on my terminal and I'm not getting exactly what I want, my goal is to loop for each JSON files and determine if the JSON file is empty or not empty.

#!/bin/bash

file_json=$(find /inputs/resource/*/*.json | awk -F'/' '{ print $(NF) }' | sort -n)

echo "Checking JSON file content."
for file in "$file_json"; do
    echo "$file"
    if [[ ! -s "file" ]]; then
        echo "JSON file is empty."
        exit
    fi
        echo "JSON file is not empty."
done

Here's the output from my terminal, it only proceeds on "JSON file is empty." even my JSON file has contents inside, and I also notice that it is not looping for each JSON files to check if the JSON file is empty or not empty, where did my bash script go wrong?

Checking JSON file content.
xpm1.json
xpm2.json
xpm3.json
JSON file is empty.

Solution

  • There are several issues with your script:

    The consequence of all this is that you iterate only once with only one file value (with 3 lines in it):

    xpm1.json
    xpm2.json
    xpm3.json
    

    This single value is printed, the if [[ ! -s "file" ]]; then test succeeds because there is no such file, so the JSON file is empty. message is printed and the script exits.

    But you don't need all this. Let's assume that "empty" means "0 byte"; using just find you can try:

    find /inputs/resource -maxdepth 2 -mindepth 2 -type f \
      -name '*.json` -printf '%f\nJSON file is ' \
      \( -size +0c -printf 'not ' -o -true \) -printf 'empty.\n'
    

    If you prefer pure bash:

    #!/bin/bash
    
    echo "Checking JSON file content."
    for file in /inputs/resource/*/*.json; do
        echo "${file##*/}"
        if [[ ! -s "$file" ]]; then
            echo "JSON file is empty."
        else
            echo "JSON file is not empty."
        fi
    done