删除和压缩目录中的文件

wko9yo5t  于 2022-10-17  发布在  Unix
关注(0)|答案(1)|浏览(156)

# ! /usr/bin/bash

DIRECTORY=/main/dir/sub-dir

if [ -d $DIRECTORY ]; then
      find $DIRECTORY/ '*' -maxdepth 1 -mtime +1 -exec rm -rf {} \;;

# Zip Files generated within the last six hour

      find $DIRECTORY/ '*' -maxdepth 1 -mmin -360 -exec gzip {} \;
   fi

I'm using this command to remove files generated within the last , however the output has the following errors

Error messages :

-bash-4.2$ ./zip_files.sh
find: â*â: No such file or directory
gzip: /main/dir/sub-dir is a directory -- ignored

Files in this directory will be of these sequence, 

-rw------- 1 postgres dba 16777216 Sep 23 23:37 000000010000224300000015
-rw------- 1 postgres dba 16777216 Sep 23 23:37 000000010000224300000016
-rw------- 1 postgres dba 16777216 Sep 23 23:37 000000010000224300000017
-rw------- 1 postgres dba 16777216 Sep 23 23:37 000000010000224300000018
-rw------- 1 postgres dba 16777216 Sep 23 23:37 000000010000224300000019
-rw------- 1 postgres dba 16777216 Sep 23 23:37 00000001000022430000001A

我只想删除已删除的文件,并压缩错误消息
感谢您的回复。

j8ag8udp

j8ag8udp1#

您的脚本可能如下所示。注意引号,注意un引号*不带空格的用法,注意find参数,参见man find。使用shellcheck检查您的脚本!


# !/usr/bin/env bash

# prefer upper case variables only for exported variables

directory=/main/dir/sub-dir
if [[ -d "$directory" ]]; then
      find "$directory"/* -maxdepth 1 -type f \
          '(' -mtime +1 -delete ')' -o \
          '(' -mmin -360 -exec gzip {} ';' ')'
fi

使用bash数组,您可以在长参数行之间放置注解:

cmd=(
          find "$directory"/* -maxdepth 1 -type f
          # delete somthing
          '(' -mtime +1 -delete ')' -o
          # gzip them
          '(' -mmin -360 -exec gzip {} ';' ')'
      )
      "${cmd[@]}"

相关问题