5

I am using Ubuntu 12.04 and I am here to know: is there any way to limit the life time of a file?

I mean, for example, I have created a file that has to be automatically deleted 10 minutes after I close it. Is there any way to do it?

Eric Carvalho
  • 54,385
Raja G
  • 102,391
  • 106
  • 255
  • 328

2 Answers2

4

You need to write a script to perform this.

Using the commands

  • access (read the file's contents) - atime
  • change the status (modify the file or its attributes) - ctime
  • modify (change the file's contents) - mtime

  • cron

  • find

Sample Script to remove the '.bak' file

 #!/bin/bash
  find <location> -mtime <value> -type f -name "*.bak" -exec rm -f {} \;

Change the permission of the script (execute)

add the script to cron and make it run when needed.

devav2
  • 36,312
4

This can be easily accomplished using inotifywait from inotify-tools package (it's not installed by default):

inotifywait -e close /path/to/file && sleep 600 && rm /path/to/file

This will set up a watch on /path/to/file and wait for it to be closed. Then after 10 minutes (600 seconds) the file will be removed.

Here's a script to make things easier:

selfdestroy.sh:

#!/bin/bash
if [ $# != 2 ]; then
        echo "$0 <file> <time>"
        exit 1
fi

if [ ! -f $1 ]; then
        echo "File $1 not found."
        exit 1
fi

if (( $2 < 1 )); then
        echo "Time must be > 0."
fi

(inotifywait -e close $1
sleep $2
rm $1) 2>1 >/dev/null &

Call the script like this: selfdestroy.sh /path/to/file 600.

Eric Carvalho
  • 54,385