5

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

9

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)"
2

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 to rm 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
0

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 in ls's output. Never parse ls. Use find. 2) On a file containing a space or a tabulation, since awk '{print $NF}' will only print the last space/tab-separated word. – kos Nov 12 '15 at 8:18

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.