I'm trying to figure out how best to approach this script, and I have very little experience, so I could use all the help I can get. :wall:
I regularly need to delete files from many directories.
A file with the same name may exist any number of times in different subdirectories.
When I perform the deletion, I will have a list of the upper level directories I want to delect the file path from, and a list of pathed files I want to delete from those directories only.
What would be the best way to set this up with the two input files?
This should get you started you might want to implement more actions (like prompt) and perhaps control which actions occur with command line args check out getopts
if [ $# -ne 2 ]
then
echo "usage: $0 list_file dir_file"
exit 1
fi
LIST_FILE=$1
DIR_FILE=$2
if [ ! -f "$LIST_FILE" ]
then
echo "unable to open list_file: $LIST_FILE"
exit 2
fi
if [ ! -f "$DIR_FILE" ]
then
echo "unable to open dir_file: $DIR_FILE"
exit 3
fi
found=0
for action in list count del
do
for del_dir in $(cat $DIR_FILE)
do
for del_path in $(cat $LIST_FILE)
do
[ -f ${del_dir}/${del_path} ] && case $action in
count) let found=found+1 ;;
list) echo " ${del_dir}/${del_path}" ;;
del) rm ${del_dir}/${del_path} ;;
esac
done
done
if [ $action = "count" ]
then
[ $found -eq 0 ] && echo "No files found to delete" && exit 5
printf "OK to delete %d file(s) (Y/N)? " $found
read ans
[ "$ans" != "Y" -a "$ans" != "y" ] && exit 0
fi
done
If interactivity is not required, if there are no blank lines in either file, and if your pathnames (both directories and files) do not contain any whitespace:
PROCEED WITH CAUTION: I cannot emphasize that enough. If the rm commands printed are acceptable, remove the word "echo" to delete the files. Error messages from non-existent files are harmless. To silence them, append 2>/dev/null (or redirect to some other file).