Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete files older than x seconds (not days, hours or minutes) on shell?

Tags:

bash

awk

There are many questions on how to delete files older than x minutes/hours/days on linux, but no one get to the seconds resolution.

I've found this solution:

for file in `ls -ltr --time-style=+%s | awk '{now=systime(); del_time=now-30; if($6<del_time && $5=="0") print $7}'` ;do
   rm -f $file >/dev/null 2>&1
done

But systime() is not present on awk

"function systime never defined"

but is on gawk which I couldn't install on Ubuntu 13.xx (and really don't whant to install any extra software).

like image 313
Parmaia Avatar asked Jul 23 '14 11:07

Parmaia


People also ask

How do I delete files older than X minutes Linux?

The -mmin stands for the modification time, and +15 means we want files that were last modified 15 minutes ago or earlier. The action flag -delete asks find to delete all the files it finds. We should note that this will look recursively through the file system hierarchy, starting from the current working directory.

How do I delete files older than x days?

Open Start on Windows 10. Search for Command Prompt, right-click the result and select the Run as administrator option. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -30 to select files with a last modified date.

How do I delete files and folders older than x days Linux?

We mention rm {} to delete all files older than 7 days, in /data/ folder. If you want to delete only folders, add type -d option to find folders, and use rmdir command. If you want to delete both files & folders, use rm -r command.

How do you delete files older than date in Unix?

For just files find /path ! -type f -newermt "YYYY-MM-DD HH:MM:SS" -delete .


1 Answers

Parsing output of ls is always a bad approach. Especially when find from GNU Findutils is able to do all the work by itself:

$ find -not -newermt '-30 seconds' -delete
like image 172
Dmitry Alexandrov Avatar answered Oct 21 '22 08:10

Dmitry Alexandrov