Why does my script not work? (Noob Alert)

I am a scripting noob and I have tried to search on google, but cannot find the answer as to why this script doesn't work properly.

The idea of this script is that it will list all files starting with f in a certain folder, and delete all but the three newest one. I am trying to achieve this by doing command "ls -t" so the newest come out on top. Then I simply skip the first 3 and start deleting what comes after (in the supplied script I am just renaming the files). For some reason when the counter hits 10, it seems to think that it a smaller value than 3. I think it only sees the 1st character of 10, leading it to think its value is 1? Yet when I echo $counter, it says 10?

I am sure you are going to slap me around the ears with one-line scripts that do the job, but as I am trying to learn I would really like to see why mine does not work as well. I really do apreciate any kind of input. Thanks in advance.

My script:

#!/bin/bash
declare -i counter=1
for file in $(ls -t f*); do
if [[ $counter > 3 ]]; then
mv $file $file.del
fi
let counter=$counter+1
done
exit 0

#!/bin/ksh

for file in $(ls -t1 f* | sed -e ':a' -e '$d;N;2,3ba' -e 'P;D'); do
    mv "$file" "$file.del"
done

sed1liners

Modifying your program rather then one liner:-)

#!/bin/bash
declare -i counter=1
for file in $(ls -t t*); do
if [ $counter -gt 3 ];then
mv $file $file.del
fi
counter=`expr $counter + 1`
done
exit 0

@push, Great! that works, thanks as now I can work out what I have been doing wrong. :b:

@vgersh99 thanks for you input too, I will be having a look at this tonight to see how it works. I am a bit disapointed it wasn't a one liner though :smiley:

#!/bin/bash

for file in $(ls -t t*| head -3)
do
  mv $file $file.del
fi

exit 0