How to find out if there are files in a folder and exit accordingly (in KSH)

To follow up on Stéphane Chazelas's comment to Kusalananda's answer:

$ ksh
$ echo ${.sh.version}
Version AJM 93u+ 2012-08-01
$ ls
TABLE1.csv  TABLE2.csv

Use an array to hold the files. Start with a glob expression that matches some files:

$ typeset -a files
$ files=( ~(N)*.csv )
$ echo "${#files[@]}"
2
$ typeset -p files
typeset -a files=(TABLE1.csv TABLE2.csv)

Now a "bare" glob that does not match to demonstrate that a non-matching glob is replaced by the glob pattern as a string:

$ files=( *.txt )
$ echo "${#files[@]}"
1
$ typeset -p files
typeset -a files=('*.txt')

Now with the "null glob" prefix

$ files=( ~(N)*.txt )
$ echo "${#files[@]}"
0
$ typeset -p files
(empty output)
$

See the File Name Generation section of your ksh man page.


To reply specifically to your question:

typeset -a contents=( ~(N)"$gp_path"/ALLSTUFF*.zip )
if [[ ${#contents[@]} -eq 0 ]]; then
    print 'EMPTY'
    exit 0
else
    print 'NOT EMPTY'
fi

You should get out of the habit of using ALLCAPS variable names.

See also: https://mywiki.wooledge.org/ParsingLs


You can make the error message disappear with 2>/dev/null inside the ls.

You can then check to see if $CONTENTS is empty with -z

CONTENTS=$(ls -d -- "${gp_path}ALLSTUFF"*.zip 2>/dev/null)
if [ -z "$CONTENTS" ]; then
    print 'EMPTY'
    exit 0
else
    print 'NOT EMPTY'
fi

To detect whether a filename pattern expands to anything, you may use

set -- "$gp_path"ALLSTUFF*.zip

if [ -e "$1" ]; then
    echo matched something
else
    echo did not match anything
    exit 1
fi

The set command sets the positional parameters to the filenames matched by the pattern, and if the first matched filename exists, then it matched something. The pattern remains unexpanded if it didn't match anything.

This would be usable in ksh, bash and any other sh-like shell.

Tags:

Linux

Ksh