0

I need to check if there are 12 files landed in a dir. This loop works fine when there is a one file and it will loop 4 times with "sleep 300". but when there are no files at all, it fails and does not loop. what else can I add to make it loop even with NO files at all. In short, I want to check 20 mins for file delivery.

retry() {
attempt_num=0
    while [[ `ls -1 *File*${JulianDate}.* | wc -l` -lt 12 ]]
    do
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

3

Don't parse ls output. Read the list of files into an array, and check the size of the array.

retry() {
    while true; do
        files=( *File*${JulianDate}.* )
        (( ${#files[@]} >= 12 )) && break
        sleep for some amount
    done
    do stuff with 12 or more files ...
}
glenn jackman
  • 85,964
3
waitforfiles () {
    n=0
    while [ "$n" -lt 4 ]; do
        set -- *File*$JulianDate.*
        [ "$#" -ge 12 ] && return 0
        sleep 300
        n=$(( n + 1 ))
    done

    return 1
}

if ! waitforfiles; then
    echo 'Not enough files arrived in time.' >&2
    exit 1
fi

# Do something here.

Don't parse the output of ls, it is only for you to look at. Instead, use the shell to match the names that you want to match, and then count the number of files that matches. The shell gives this to you for more or less free (in comparison to calling the external utilities ls and wc).

The function above will sleep for 300 seconds and try again, until the pattern matches 12 or more filenames or until the loop has run four times. It returns success (zero) or failure (non-zero) depending on whether the files arrived in time or not.

Related:

Kusalananda
  • 333,661