Command script for checking a file existence

Hello,

I have a directory where sometimes appear a certain file name - and I'd like to be notified by email when that happens... so what command or script I may use?

e.g. if there's a file named "adam" in the directory named "dir1" then send a mail to "abc@abc.com".. it needs to permanently check the "dir1" until the file "adam" appears and then it can stop or finish. In case, no such file name is in "dir1" it does nothing, it's just running...

Thanks!

[ -e /path/to/file ] && echo "File exists" | sendmail "abc@abc.com"

If you don't have a sendmail installed already, you'll need to install and configure something like ssmtp or postfix to get one. ssmtp is a "stub" mail server that just forwards email to a real mail server, postfix is a full-fledged mail server in its own right.

1 Like

In linux the inotifywait command was meant to do exactly what you want. A few linuxes do not have the command installed by default, but it is available for the distro. Since I do not know what OS you have exactly, there is not much point to explaining this issue further.

inotifywait will write notification to the syslog or execute a script. UNIX.com not a coding service, we try to help you get the skills and understanding you need to do things well.
See:
inotify-tools

1 Like

Thanks, is it possible to make this command run and stop only if the file exist? So that when the certain file appears, the script sends the email and stop/exit. Because when I run this command it finishes running no matter if file exists or not...

while [ ! -e /path/to/file ] ; do sleep 5 ; done
echo "File exists" | sendmail "abc@abc.com"

But the more complex you make it, the better it'd be to use inotifywait instead.

1 Like

I'm grateful for you brother, thanks alot for the quick response, this is much cleaner and easier to understand.