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
  • http://mywiki.wooledge.org/ParsingLs – muru Jan 19 '17 at 13:20
  • 4
  • 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
  • @ZumodeVidrio That is true, how can I delete it on FTP server? – Ivan Topić Jan 19 '17 at 13:26
  • 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
  • @muru Not a dupe. OP wants to delete on the FTP server and via FTP. – xhienne Jan 19 '17 at 15:17
  • @xhienne since OP can access the server without FTP to run shell commands, I don't see why it has to be FTP – muru Jan 19 '17 at 15:28
  • @muru Didn't see where this is written. But the code posted in the question, and the text that folllows, show clearly that the OP wants to clean-up things remotely with lftp. – xhienne Jan 19 '17 at 15:44
  • @xhienne "I tested it in the terminal inside a test folder on VPS..." And OP might "want" to do X, but that doesn't mean Y isn't the better solution. Not interested in arguing further. – muru Jan 19 '17 at 15:48

0 Answers0