1

I would like to create a cron job for deleting the oldest file in a directory which is on FTP server. I have created my first shell script

#!/bin/sh

# connect to backup FTP server...
lftp -u (username),password backup.contabo.net << EOF
cd /backups
ls

EOF

This is what I get http://image.prntscr.com/image/72a86bf453c849a8af4a3340e4936172.jpeg

I did some searching and the following line worked when I tested it in the terminal inside a test folder on VPS (with some newly created .txt files):

rm "$(ls -t | tail -1)"

...but when I place it inside the shell script and when I run it with bash testing.sh I get

rm: Access failed: 550 index.php: No such file or directory

Why is the script trying to delete index.php? I don't even see it inside file listing. It should delete 01December_01_2016_html.tar

EDIT Ok I finally succeeded to delete file but with manually writing the filename.

rm /backups/01December_01_2016_html.tar

So I was thinking to first create a variable with the filename so I can pass it to rm /backups/$FILENAME.tar or similar, I haven't done this because the following code is giving me the error - Unknown command 'FILENAME="testing.sh" This is basically the same thing, it means I get the latest file on local directory and not in the FTP directory (even though single ls worked OK for retrieving all files)

FILENAME="$(ls -t | tail -1)"
echo $FILENAME
  • mywiki.wooledge.org/ParsingLs – muru Jan 19 '17 at 13:20
  • 4
    Possible duplicate of Shell script for moving oldest files? – muru Jan 19 '17 at 13:20
  • Set 1st line to be #!/bin/sh – Romeo Ninov Jan 19 '17 at 13:21
  • 2
    I think you want to delete a file inside of a FTP server, right? Perhaps with your rm of your ls output you are getting the file from your local directory (which may have the index.php file), not the remote directory, do you have it? – Zumo de Vidrio Jan 19 '17 at 13:25
  • 3
    You'll need to write a shell script that first queries the FTP server for the directory listing, then sorts out what file is the oldest, then issues the rm to the FTP server. That's two separate transactions to the FTP server, but you can't run a shell script "on the FTP server". – Kusalananda Jan 19 '17 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.