I’m working on a bash script to delete files and directories that are older than 1 day, excluding specific files and directories from deletion. When I hardcode the paths to exclude in the find command, it works correctly. However, when I construct the exclusion command dynamically using a variable (PRUNE_CMD), the results are not correct.
Working script:
find "$TARGET_DIR" ( -path "/home//a" -prune -o -path "/home//b" -prune -o -path "/home//c" -prune -o -path "/home//d" -prune -o -print ) -type f -mtime +1
Below is my script
#!/bin/bash
# Configurable target directory
TARGET_DIR="/home/****"
# Directories and files to exclude
EXCLUDE_DIRS=(
"/home/****/a"
"/home/****/b"
"/home/****/c"
"/home/****/d"
)
EXCLUDE_FILES=(
"/home/****/**/a.txt"
"/home/****/**/b.log"
)
#Construct the prune command for directories
PRUNE_CMD=""
for DIR in "${EXCLUDE_DIRS[@]}"; do
PRUNE_CMD="$PRUNE_CMD -path $DIR -prune -o"
done
# Construct the prune command for files
for FILE in "${EXCLUDE_FILES[@]}"; do
PRUNE_CMD="$PRUNE_CMD -path $FILE -prune -o"
done
# Add final condition to exclude nothing further
PRUNE_CMD="$PRUNE_CMD -false"`
# Find and print files older than 1 days, excluding the specified directories and files
echo "Files older than 1 days to be deleted (excluding specified):"
find "$TARGET_DIR" ( $PRUNE_CMD ) -type f -mtime +1 -print
# Find and print directories older than 1 days, excluding the specified directories and files
echo "Directories older than 1 days to be deleted (excluding specified):"
find "$TARGET_DIR" ( $PRUNE_CMD ) -type d -mtime +1 -print
New contributor
Kavita Khulbe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.