I want to make a bash script to delete the older file form a folder. Every time when I run the script will be deleted only one file, the older one. Can you help me with this? Thanks
3 Answers
As Kos pointed out, It might not be possible to know the oldest file (as per creation date).
If modification time are good for you, and if file name have no new line:
rm "$(ls -t | tail -1)"
-
How to delete last 10 oldest files? as the above comment gives error for more than 1 file– iCyborgFeb 23, 2021 at 15:11
-
replace
tail -1
bytail -10
can you give us the error ? have you special file name ? (new line, semicolon or the like ?) are there sub directories ? (this will breakrm
)– ArchemarFeb 23, 2021 at 15:16 -
what if I have space or newline in file name?! nope it will crash /-: Oct 3, 2021 at 20:27
It looks like you're fine with deleting the oldest modified file instead of the oldest created file;
I consider this to be the safest method, as it won't break on filenames containing newlines:
stat --printf='%Y %n\0' * | sort -z | sed -zn '1s/[^ ]\{1,\} //p' | xargs -0 rm
stat --printf='%Y %n\0' *
: prints a NUL-separated list of the last modification's time followed by the file's path for each file in the current working directory;sort -z
: sorts the list using NUL as the line separator;sed -zn '1s/[^ ]\{1,\} //p'
: removes the first occurence of a string containing one or more characters not a space followed by a space from the first NUL-terminated line and prints it;xargs -0 rm
: passes the NUL-terminated line torm
as an argument;
% touch file1
% touch file2
% stat -c '%Y %n' *
1447318965 file1
1447318966 file2
% stat --printf='%Y %n\0' * | sort -z | sed -zn '1s/[^ ]\{1,\} //p' | xargs -0 rm
% ls
file2
To determine the oldest file according to "Access Time" or "Modify Time"?
If it is the second, then just use the following command:
rm ls -l --sort=time | sed -n 2p | awk '{print $NF}'
-
As you noted already,
ls
's output can be sorted either by atime or mtime, as creation time is not supported by the kernel (and a method to remove the last created file is what the question is asking for by the way); but mostly this can break 1) On a file containing a newline inls
's output. Never parsels
. Usefind
. 2) On a file containing a space or a tabulation, sinceawk '{print $NF}'
will only print the last space/tab-separated word.– kosNov 12, 2015 at 8:18
ls -1t | tail -n +11 | xargs rm -f