Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 脚本删除目录中的所有文件,然后发送电子邮件_Linux_Bash_Shell - Fatal编程技术网

Linux 脚本删除目录中的所有文件,然后发送电子邮件

Linux 脚本删除目录中的所有文件,然后发送电子邮件,linux,bash,shell,Linux,Bash,Shell,需要一个脚本来删除一个目录中的所有文件,然后电子邮件一旦完成,我有以下作为模板,但不确定这是否会工作-当然没有电子邮件组件已添加 #!/bin/sh DIR="/var/www/public_html/docs/files/" LIST=`ls -l $DIR | grep -v "total 0"` FILES=`ls $DIR` cd $DIR if [ -z "$LIST" ] then exit else echo "Files Delete:" echo $FILES

需要一个脚本来删除一个目录中的所有文件,然后电子邮件一旦完成,我有以下作为模板,但不确定这是否会工作-当然没有电子邮件组件已添加

#!/bin/sh
DIR="/var/www/public_html/docs/files/"
LIST=`ls -l $DIR | grep -v "total 0"`
FILES=`ls $DIR`
cd $DIR
if [ -z "$LIST" ]
then
  exit
else
  echo "Files Delete:"
  echo $FILES
  rm -f *
fi
更新:

#!/bin/sh
DIR="/home/test/test/docs/test/"
cd $DIR
rm -f *
一些注意事项:

您使用所有caps DIR、LIST和文件,但按照惯例,shell脚本中的所有caps变量都是环境变量。你应该使用例如

dir='/var/www/public_html/docs/files/'
相反

要查找目录中有多少文件,请使用

find "$dir" -maxdepth 1 -type f | wc -l
您同时使用列表和文件;在删除文件之前,您似乎正在尝试找出是否存在任何文件。从功能的角度来看,这没有任何意义,但是如果您必须有条件地响应文件列表,那么最好以这种方式做出决定

if [ $(find "$dir" -type f | wc -l) -gt 0 ] ; then
    echo Files Delete:
    find "$dir" -printf '%f '
fi
尽管您应该知道,此输出不能可靠地用于重建实际文件名

要实际删除文件,应再次使用
find

find "$dir" -maxdepth 1 -type f -delete
把它们放在一起

dir='/var/www/public_html/docs/files/'

if [ $(find "$dir" -type f | wc -l) -gt 0 ] ; then
    echo Files Delete:
    find "$dir" -maxdepth 1 -type f  -printf '%f ' -delete
fi

在这里,我将“打印文件”和“删除文件”两个步骤合并到一个调用
find

的过程中,为什么您的代码要跳过所有这些障碍?
rm-f/var/www/public\u html/docs/files/*
rm-f“$DIR*”
是否足够?为什么不试试看会发生什么?我希望
rm-f*
可以正常工作。
find/var/www/public\u html/docs/files/-type f-delete
在这里可能是最好的。感谢我将脚本更改为非常基本的nownon risk ist改为
cd$DIR
,而没有检查对DIR的更改。之后,您希望删除所有文件。如果你的目录不存在怎么办?如果运行此脚本的用户无法访问该目录,该怎么办?