Codeme
Codeme

Reputation: 147

Delete a newly created file using shell script after 5 minutes

I am writing a shell script where I create a file ABC.txt in a path /path/to/ABC/ABC.txt.
Now I at the end of the script, I want to schedule a cron job to delete this file after 5 minutes (just once, not recurring).
I cannot ad sleep of 5 minutes in this script as it is being used by multiple users on server for multiple paths/files. And 5 minutes after the user executes this script the corresponding file.txt from respective path should get deleted.

What I read from a cronjob is you can trigger a script using crontab -e and then providing periodic notation of job and path to script H/5 * * * * /bin/sh /path/to/ABC/ABC.txt.

Can someone tell me how to schedule such functionality using cron. If there is a better way to do this please suggest.

Upvotes: 0

Views: 1102

Answers (1)

kvantour
kvantour

Reputation: 26481

Using at command:

#!/usr/bin/env bash
script_path="$(realpath -s -- "$0")"
# start script
...
# end script
echo "rm -- \"$script_path\"" | at "now + 5 minutes"

Using background process with sleep:

#!/usr/bin/env bash
script_path="$(realpath -s -- "$0")"
# start script
...
# end script
( sleep 300 && rm -- "$script_path" ) &

Using parent selfdestruct process:

Write a little script selfdestruct that looks like:

#!/usr/bin/env bash
dt="$1"; shift
"$@"
( sleep "$dt" && rm -- "$1" ) &

and run your script with

$ selfdestruct 300 /path/to/script arg1 arg2 arg3

Upvotes: 3

Related Questions