Issue
#! /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
i only want to remove the files removed and gzipped and compress the Error messages
Appreciate your response in replying back.
Solution
Your script could look like the following. Note the quotes, note the usage of unquoted *
without a space, note the find
arguments, see man find
. Check your script with 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
With bash arrays you can put comments between long argument lines:
cmd=(
find "$directory"/* -maxdepth 1 -type f
# delete somthing
'(' -mtime +1 -delete ')' -o
# gzip them
'(' -mmin -360 -exec gzip {} ';' ')'
)
"${cmd[@]}"
Answered By - KamilCuk Answer Checked By - Pedro (WPSolving Volunteer)