Sanitarium by Zac Dreyer

Delete multiple remote files and directories via ftp

Posted by zac on Friday, December 28th, 2012

Having to delete multiple files or directories on a remote server via shell ftp can be a tad annoying. delete [filename] and rmdir [directory] is just going to get a tad much, specifically when you have you have files within directories and sub-directories. The solution to this one is finding a way to recursively delete remote files directories.

First up we have the standard ftp client, here we would be using the mdelete command.

$ ftp -i <server>
ftp> <user>
ftp> <pass>
ftp> mdelete <wildcard><filename><wildcard>

Example: ftp> mdelete *.jpg

The only problem with this command is that it will recursively delete files matching the specified pattern, including wildcards, but will not remove folders. You would need to delete them manually with rmdir, not very efficient.

Next up we have lftp installed and will be using this client to delete multiple files / directories. This is a tad more complicated as we would need to use 2 commands in the same line in order to achieve the desired result.

$ lftp -u <user>,<pass> <server> 
lftp> glob -a rm -r ./<path>/<wildcard><file-or-directory-name><wildcard>

Example: glob -a rm -r ./*images*

rm on it’s own does not support wildcards, the solution is to either use mrm (which I couldn’t get going correctly) or to include the glob command before the rm command.

Extract from man page for LFTP:

glob [-d] [-a] [-f] command patterns

       Glob  given patterns containing metacharacters and pass result to given command.  E.g. ``glob
       echo *''.

            -f   plain files (default)
            -d   directories
            -a   all types

rm [-r] [-f] files

       Remove remote files.  Does not expand wildcards, use mrm for that. -r is for recursive direc‐
       tory  remove.  Be careful, if something goes wrong you can lose files. -f suppress error mes‐
       sages.


man page Source: http://lftp.yar.ru/lftp-man.html

Posted in: Featured, Linux.

Comments are closed.