Bash script to remove the oldest file from from a folder

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

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