General
cancel
Showing results for 
Search instead for 
Did you mean: 

Verify if [ -f file_mask*] for group of files

SOLVED
Go to solution
Victor Mo
Occasional Contributor

Verify if [ -f file_mask*] for group of files

I have a ksh script that does `ls /dir_name/file_mask*`

How can I check if any of files returned at all, I tried and found that if [-f ..] works only for single file.

I'm thinking to > all output to some tmp.file and then check its size, but probably there is a better way.

Txa
all

v
5 REPLIES
Steven Schweda
Honored Contributor
Solution

Re: Verify if [ -f file_mask*] for group of files

As usual, many things are possible. For
example:

bash$ ls -1 cxx
a.cpp
a.h
b.cpp

files=` ls cxx/*.cpp 2> /dev/null `
bash$ if [ -n "$files" ] ; then echo 'FILES' ; else echo '(none)' ; fi
FILES

bash$ files=` ls cxx/*.xyz 2> /dev/null `
bash$ if [ -n "$files" ] ; then echo 'FILES' ; else echo '(none)' ; fi
(none)

"find" might be useful, too.
Randy Jones_3
Trusted Contributor

Re: Verify if [ -f file_mask*] for group of files

I tend to use

filecount=`ls -1 mask* | wc -l`

then test the returned count. Tweak as necessary if dot files are involved.
Keith Bryson
Honored Contributor

Re: Verify if [ -f file_mask*] for group of files

Try:

ls /dir_name/file_mask* >/dev/null ; echo $?

You will only get a 0 return code if "ls" lists any files. So put this in a script and you could have:

if [ `ls /dir_name/file_mask* >/dev/null ; echo $?` = 0 ]
then
echo "We have files!!"
else
echo "NO FILES FOUND!!!"
fi

Hope that helps.
Keith
Arse-cover at all costs
Keith Bryson
Honored Contributor

Re: Verify if [ -f file_mask*] for group of files

Just to make sure, you should also redirect STDERR to /dev/null:

... >/dev/null 2>&1 ; echo $? ...

Keith
Arse-cover at all costs
Steven Schweda
Honored Contributor

Re: Verify if [ -f file_mask*] for group of files

> You will only get a 0 return code [...]

Good point.

> if [ `ls /dir_name/file_mask* >/dev/null ; echo $?` = 0 ]

But there's no need to drag in "[" ("test"),
if the command's exit status is the
criterion:

if ls /dir_name/file_mask* > /dev/null 2>&1

For example:

bash$ if ls cxx/*.cpp > /dev/null 2>&1 ; then echo 'FILES' ; else echo '(none)' ; fi
FILES

bash$ if ls cxx/*.xyz > /dev/null 2>&1 ; then echo 'FILES' ; else echo '(none)' ; fi
(none)


> As usual, many things are possible.

I stand by that.