1) Please use ***
[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do
not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.
2)
$(..) is highly recommended over `..`
3) When using
bash or
ksh, it's recommended to use
[[..]] for string/file tests, and
((..)) for numerical tests. Avoid using the old
[..] test unless you specifically need POSIX-style portability.
http://mywiki.wooledge.org/BashFAQ/031
http://mywiki.wooledge.org/ArithmeticExpression
4)
parsing ls for filenames and metadata is not recommended. If you want to know how many files are in a directory, you can use an array.
Code:
files=( * )
if (( ${#files[@]} > 3 )); then
rm "${files[@]: -3}" #removes the last 3 files in the file list
fi
How can I use array variables?
http://mywiki.wooledge.org/BashFAQ/005/
Although the above simply relies on the shell's default sorting. If you can ensure that all the files have the same pattern and their date directly in their filename in YYYY-MM-DD form, then this would be just fine.
Otherwise you'll have to run them through a loop to test the metadata, or else use
find.
How can I find the latest (newest, earliest, oldest) file in a directory?
http://mywiki.wooledge.org/BashFAQ/003
http://mywiki.wooledge.org/BashFAQ/099