Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A shell script that monitors a directory for new or moved(/renamed) images and executes a program(C program, in my case) that takes the file's location and uploads it to the server. After executing the process keeps on running in the background and watches every new file that comes.
# NOTE: To avoid any word splitting or globbing issues you should always try to use double quotes around the variable name
# Specify any new extensons or filenames over here that you want monitored for changes
FILES_MONITORED=( .+\.jpe?g .+\.png .+\.bmp .+\.JPE?G .+\.PNG .+\.BMP )
# TODO: Update the description
if [[ "$#" -eq 0 ]] || [[ "$#" -eq 1 ]]; then
printf "Upload program's location must be specified. Directory to be monitored must be specified. \n\
[USAGE]: ./ \"directory\" \"path-to-upload-file\"\n\n\
[NOTE]: Directory must have a trailing backslash i.e like ~/images/\n\n"
exit 1
# Function returns 1 if the file is an image and 0 otherwise
is_image(){ # return value is given by $?
for i in "${FILES_MONITORED[@]}"; do
if [[ "$1" =~ $i ]]; then # $i should not be in "" because it is a regex expression
return 1;
return 0;
# Checks the folder mentioned for new image files added
# TODO: Check if this can work on any directory
inotifywait -m -e create -e moved_to "$1" | while read path action file; do
echo "The file '$file' appeared in directory '$path' via '$action'";
is_image "$file"
if [[ IS_FILE_AN_IMAGE -eq 1 ]]; then
printf "Upload program = '$2'\n File = '$filepath'\n"
sleep 2
"$2" "$path$file"
done &
# Save process PID for future use in the location where the script is executed
echo "$!" > PID.txt
# TODO: Thi can be created more efficiently. I am noob atm. Help is appreciated.
# Extract the JOB id and save it to JOB.txt
jobs -l > jobslist.temp
grep -f PID.txt jobslist.temp > t1.temp
cut -d']' -f1 t1.temp > t2.temp
cut -c2- t2.temp > JOBID.txt
rm *.temp
# Making the monitor process free from terminal
disown %$( cat JOBID.txt )
# To kill the process run the following steps;-
# 1. Execute the command -
# ps -efl | grep inotifywait
# 2. Find the process of inotifywait that is running
# 3. Find the parent process id (PPID) and close that process. This is the value of 5th column from left.
# kill -9 PPID
# 4. Find the process id (PID) and close the process. Value of 4th column from left.
# kill -9 PID
# 5. Execute
# ps -efl | grep inotifywait
# to confirm the process is killed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment