Ubuntu 14.04.1.
I have a bash script, called by cron every 10 minutes, which basically looks for files in a subdir, then loops through and process each file. But how do I check if there are no files found? If there are no files found I don't want to process them, and I don't want to get an email via cron that says "no files found", because cron runs every 10 minutes. That's 144 emails per day saying "no files found" that I don't want to get.
- The input/ dir is owned by me and has full rwx permissions.
- I've already guaranteed the files in input/ do not contain spaces, thanks to another answer on Ask Ubuntu.
Here's my basic script.
#!/bin/bash
# Cron requires a full path in $myfullpath
myfullpath=/home/comp/progdir
files=`ls $myfullpath/input/fedex*.xlsx`
# How do I check for no files found here and exit without generating a cron email?
for fullfile in $files
do
done
Thanks! I didn't even know what to google for this one.
EDIT: My script is now this:
#!/bin/bash
# Script: gocronloop, Feb 5, 2015
# Cron requires a full path to the file.
mydir=/home/comp/perl/gilson/jimv/fedex
cd $mydir/input
# First remove spaces from filesnames in input/
find -name "* *" -type f | rename 's/ /-/g'
cd $mydir
shopt -s nullglob
if [ $? -ne 0 ]; then
echo "ERROR in shopt"
exit 1
fi
for fullfile in "$mydir"/input/fedex*.xlsx
do
# First remove file extension to get full path and base filename.
myfile=`echo "$fullfile"|cut -d'.' -f1`
echo -e "\nDoing $myfile..."
# Convert file from xlsx to xls.
ssconvert $myfile.xlsx $myfile.xls
# Now check status in $?
if [ $? -ne 0 ]; then
echo "ERROR in ssconvert"
exit 1
fi
perl $1 $mydir/fedex.pl -input:$mydir/$myfile.xls -progdir:$mydir
done
First things first: Don't parse
ls
.Now that we have got that out of the way, use globbing, alongwith
nullglob
:Usually with globbing, if
*
doesn't match anything it's left as is. Withnullglob
, it is replaced with nothing, so a false match isn't triggered.For example:
If you're dead-set on using
ls
anyway, despite it's unsuitability for your original code, or if you:just want to find out if
ls
didn't find any filesyou could check it's exit code. A "No such file..." will fail (exit code 2). While even an empty directory's
ls
will succeed (exit code 0):Python seems a comfortable option as well if I am not missing the point:
Let
find
do the hard work for you. Write a script that processes a file passed as the first parameter, then do this in your crontab:find
will not generate any output if it doesn't find files matching the expression.If you look at https://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash, something like that should work:
... Look also at http://mywiki.wooledge.org/ParsingLs
Why not use the find command, putting a single filename on each line: