Ubuntu – How to monitor new files in a directory and move/rename them into another directory

bashprogrammingpythonscripts

A program generates output textfiles, named output.txt, after every 15th iteration of a certain process. Doing so, it overwrites the last output.txt. I want to keep the files however, and I can't modify the file name within the program.

Can I run some script, together with the program, that monitors the output directory and moves and renames the output.txt files into another directory?

Best Answer

First install the package inotify-tools:

sudo apt-get install inotify-tools

A bash script would help

#! /bin/bash

folder=~/Desktop/abc

cdate=$(date +"%Y-%m-%d-%H:%M")

inotifywait -m -q -e create -r --format '%:e %w%f' $folder | while read file

  do
    mv ~/Desktop/abc/output.txt ~/Desktop/Old_abc/${cdate}-output.txt
  done

What does this script means:

This will watch the folder ~/Desktop/abc so whenever a file created inside then it's going to move the file founded inside which is name output.txt to a directory ~/Desktop/Old_abc and rename providing a suffix of date and time of t he new file, this to be sure not to overwrite old files and like that you can also know this file was created in what time and date

Related Question