Linux Blog

Auto Clean-up Downloaded Files – Part III

Filed under: Shell Script Sundays — TheLinuxBlog.com at 8:00 am on Sunday, January 18, 2015

In Part 2, we added some read prompts to read which directory to run the script in and used some bash if/then/else statements to do some basic input validation. This week by using the creating script parameters with getopts article we’ll enhance the script a little to remove the echo from the example to allow the user to delete the files if they choose, defaulting to not remove files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/bash
 
while getopts ":d" ARG;
do case "${ARG}" in 
d) echo "-d option set. DELETING FILES"; DELETE=true;;
esac;
done
 
# Get the Current working directory
PWD=`pwd`
 
# Get User Input
echo "Enter Directory to run in [\"$PWD\"]: " 
read inputline; 
# handle blankline (default) 
if [ -z "$inputline" ]; then
	inputline=$PWD
fi
# Check to make sure that it is a valid directory
if [ ! -d "$inputline" ]; then
   	# Doesn't exist, exit
	echo "Directory $inputline does not exist"
	exit;
fi
 
if [ ! $DELETE ]; then
	echo "Finding Files to delete in $inputline, use -d to delete"
	find "$inputline" -iname "*(?)*" | while read i; do echo rm "$i"; done;
else
	echo "Files to delete:"
	find "$inputline" -iname "*(?)*" | while read i; do echo rm "$i"; done;
	echo "Are you Sure? Y to continue"
	read confirm;
	if [ $confirm == "Y" ]; then
		find "$inputline" -iname "*(?)*" | while read i; do rm "$i"; done; echo "Done";	
	else
		echo "Cancelled"
	fi;	
fi;

As you can see above, the script has expanded quite a bit to a whopping 39 lines. Really the only parts that changed are lines 3-7 and 26-37. I’ll walk you thru the changes now. In the first section, we set up getopts to use -d for the prompt for delete, echo “Deleting” and set the DELETE variable to true, this gets used in the later section. On line 26, if DELETE is not set, then it goes ahead and just echo’s the files with the message to use -d to delete. The next section, is for if the -d switch was used, it first echo’s the files, and then uses the same read command and if statement to delete the files if the user presses Y and enter.

We’ve still got file comparisons with user interaction (keeping the latest file, renaming it to the original file name, or keeping both) and perhaps statistics to cover in future articles.