yadutaf
yadutaf

Reputation: 7132

How to delete folders whose name is less than ...?

On my server, I have a bunch of archived folder name after the date: yyyy-mm-jj This allows to easily sort the folders and find relevant data.

I would like to delete all archives done before a given data. With my folder naming, natural sort order is the same as regular sort so that I could rely on the usual bash construct:

if [ $foldername -lt "yyyy-mm-jj" ]; then
    rm -r $foldername
fi

Is there a more efficient way to do it ?

Upvotes: 2

Views: 1143

Answers (1)

[ $foldername -lt "yyyy-mm-jj" ] will always be false, because -lt is a numeric operator: the strings you're comparing aren't numbers, so they're both treated as 0. Use the < or > operator instead to compare strings (this is a ksh/bash/zsh feature). Note that there are only string operators, there is no <= or >=.

Wildcard expansion returns the matching names in lexicographic order. So to act on the oldest files, loop through the files and break out when you find a file that's too recent.

for dir in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]; do
  if ! [[ $dir < $min_date_to_keep ]]; then break; fi
  rm -r "$dir"
done

Upvotes: 5

Related Questions