Delete oldest folder based on folder named as date

Hi,

I have a script doing backup to synology server, the script create new folder each day with the date as being folder name i.e. 2018-07-30. Just before creating the new folder I want the script to find the oldest folder from the list and delete it including its content.

for example looking at the list below folder 2018-01-01 is the oldest folder as per directory naming. I want the expect code code below to find and delete it.

2018-07-30
2018-07-29
2018-07-28
2018-07-27
2018-07-26
2018-07-25
.
.
.
2018-01-01
expect << 'EOF' >> $today.log
set dir [timestamp -format "%Y-%m-%d"]
spawn sftp server@ip
expect "Password:"
send "Password\r"
expect "sftp>"
send "lcd /backup/\r"
expect "sftp>"
send "cd /BackupDirectory/\r"
expect "sftp>"
send "Here I want the code to find the oldest directory as per name and delete it\r"
expect "sftp>"
send "mkdir $dir\r"
expect "sftp>"
send "put -r /backup/$dir/*.gz /BackupDirectory/$dir/\r"
set timeout -1
expect "sftp>"
send "!rm -rf /backup/$dir\r"
expect "sftp>"
send "bye\r"
EOF
}

As your directory names are suitably formatted, you can just use ls 's inherent sort. Try

echo rm $(ls -1d 2018* | head -1)

The echo is for testing / debugging only.

BTW, you mayhap don't need the expect command for your purpose. Did you consider sftp 's -b batchfile option and ssh 's public key authentication?

1 Like

Hi Rudic,

Thank you for the answer, I just had to modify a bit in order to cover years past 2018 but your answer was correct.

rm -rf $(ls -ld [0-9][0-9][0-9][0-9]* | head -1

For your suggestion about -b batchfile and ssh's public key options I did looked into that and tried implementing that solution first. However, at that moment it was too complicated for me and did not worked out. I will look into that in near future. Do you have any guide on implementing that solution? Any input is further appreciated.

The batchfile handling might be self-explanatory, and for ssh 's public key authentication there's many a thread in these forums. The links at bottom left under "More UNIX and Linux Forum Topics You Might Find Helpful" might be helpful as well.

1 Like