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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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)"
Method 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' * | sort -z | sed -zn '1s/[^ ]{1,} //p' | xargs -0 rm
stat --printf='%Y %n' *: 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 tormas an argument;
% touch file1
% touch file2
% stat -c '%Y %n' *
1447318965 file1
1447318966 file2
% stat --printf='%Y %n' * | sort -z | sed -zn '1s/[^ ]{1,} //p' | xargs -0 rm
% ls
file2
Method 3
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}'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0