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

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

I 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() not on awk

"systime function is never defined"

but it is on gawk , which I could not install on Ubuntu 13.xx (and really do not want to install any additional software).

+6
source share
2 answers

Parsing ls output is always a bad approach. Especially when find from GNU Findutils can do all the work on its own:

 $ find -not -newermt '-30 seconds' -delete 
+16
source

The solution I found is to replace the systime() command and use date +%s as follows:

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

The trick is to capture the output of date +%s inside awk , and using cmd="date +%s"; cmd|getline now; close(cmd) cmd="date +%s"; cmd|getline now; close(cmd) cmd="date +%s"; cmd|getline now; close(cmd) was the only (really first) way I found.

Edit: I changed the parenthesis backlinks as recommended by @Jotne

-1
source

Source: https://habr.com/ru/post/972695/


All Articles