bashshell

Shell Script not entering a while loop.


#! /bin/sh

while [ ! -r '*.pdf' ]
do
        echo "No pdf files have been created in the last 5 mins."
        sleep 5
done

while [ -r '*.pdf' ]
do
    echo "The following pdf file(s) have been created in the last 5 mins:"
    find -mmin -5 -iname '*.pdf'
    sleep 5
done

Any ideas why this wont enter the second loop even if there have been some .pdf made in the last 5 mins? Probably very wrong code, any ideas are greatly appreciated!


Solution

  • Diagnosis

    For the first loop, you have:

    while [ ! -r '*.pdf' ]
    

    The test condition is looking for a file named *.pdf (no globbing; a file named precisely *.pdf) because you wrapped the name in quotes.

    For the second loop, you have:

    while [ -r '*.pdf' ]
    

    This too is looking for *.pdf (not globbing the names). So, except in the unlikely circumstance that there is a file called *.pdf, these loops are not going to work as intended.

    Prescription

    You could probably use:

    while x=( $(find -mmin -5 -iname '*.pdf') )
    do
        if [ -z "${x[*]}" ]
        then echo "No pdf files have been created in the last 5 mins."
        else
            echo "The following pdf file(s) have been created in the last 5 mins:"
            printf "%s\n" "${x[@]}"
        fi
        sleep 5
    done
    

    This uses an array assignment to give you a list of names. It isn't perfect; if there are blanks in file names, you'll end up with broken names. Fixing that isn't completely trivial. However, carefully choosing "${x[*]}" to manufacture a single string from the names in the array (if there are any), we can test for new files. When the new files are found, report their names on separate lines using printf and "${x[@]}", which gives you one name per line of output.