Deleting files in a server using shell script

2019-07-02 01:02发布

问题:

How do you delete a file in a server after doing a wget of all the files?
I understand the delete command works, when you are have done a ftp into the server, but I am unable to use the command while running a shell script. Below is my script, kindly let me know what is wrong in it.

#!/bin/bash

filelist='ls *20120330*'
for file in $filelist
do
ftp -vn <$hostname> <<EOFD
  quote USER <username>
  quote PASS <Pass>
binary
 ls -lrt *20120330*
 delete $filelist
quit
EOFD
done

回答1:

You want

for file in *20120330*

rather than a loop over the literal words ls and *20120330*. If your real use case is much, much more complex, there could be a reason you want the file list in a variable, but my guess is that you don't, and never will.

(What you were probably thinking was

for file in `ls *20120330*`

but that is also wrong, for different but related reasons. See also http://porkmail.org/era/unix/award.html#ls)

Tangentially, you are probably better off creating a script which deletes all the file names, rather than creating a new ftp session for each file you want to remove;

#!/bin/bash

dellist=
nl='
' # yeah, nl is a newline in single quotes
for file in *20120330*
do
    dellist="delete $file$nl"
done
ftp -vn <$hostname> <<EOFD
  quote USER <username>
  quote PASS <Pass>
  binary
  ls -lrt \*20120330\*
  $dellist
  quit
EOFD


回答2:

Try using rm instead of delete



回答3:

If it's an option, I'd recommend using ncftpget instead of regular ftp, as it has features that make it friendlier to scripting like this.



回答4:

ftp command

prompt
mdel  *20120330*


回答5:

#!/bin/bash
username=luser
password=secret
hostname=localhost

filelist=`ls *20120330*`
for f in $filelist; do
ftp -vn ${hostname} <<EOFD
  USER ${username}
  PASS ${password}
  binary
  ls -l ${f}
  delete ${f}
  quit
EOFD
done


标签: bash shell unix