Deleting the oldest file in a directory

Hey! I have found similar posts both here and on other sites regarding this, but I cannot seem to get my script to work. I want to delete the oldest file in a test directory if there are more than two files. My script is currently:

#!/bin/bash

MEPATH=/usr/local/bin/test

FILECOUNT=`ls $MEPATH | wc -l`;
if [ $FILECOUNT > 2 ]
then
        cd "$MEPATH" && ls -tr | head -n 1 | xargs rm -f;
        echo "Removed oldest file...";
else
        echo "There were not more than two files, nothing to remove";
fi

When I run the script, it removes the oldest file regardless of whether or not there are more than two files, and places an empty file called "2" in the directory. Any ideas on how to fix this? Thanks.

Modify the below lines and change the comp operator

FILECOUNT=`ls -1 $MEPATH | wc -l`;

Your problem is this line:

if [ $FILECOUNT > 2 ]

To the shell it means: test ([]) the variable FILECOUNT for existence and if it has a value, and redirect any output to the file named '2' (> 2). If you're using the single bracket form of the tests, you'll have to use

  • -gt instead of >
  • -lt instead of <
  • -ge instead of >=
  • -le instead of <=
  • -ne instead of !=

You can get a list of all test operators by looking at the man page of test.

---------- Post updated at 09:26 ---------- Previous update was at 09:21 ----------

@dennis.jacob: the parameter '-1' to ls won't change anything. If ls detects that output does not go to a terminal it automatically switches to single-column mode. You can easily test that by running

ls | cat

in any directory.

Thanks pludi; this fixed the problem. I forgot about operators for [] versus something like [[]]. :b:

Yes pludi, Its my mistake. Thank you for pointing that.