Linux Blog

Auto Clean-up Downloaded Files – Part II

Filed under: Shell Script Sundays — at 8:00 am on Sunday, January 11, 2015

Last week I showed a one liner that could be used to remove duplicate files from your downloads folder. Using previous Shell Script Sunday articles, over the next few weeks we’ll add some additional functionality to make it a little more functional.

On its own the snippet is not that useful. The script will only run in the current directory. Adding a prompt to ask the user what directory to run in, or defaulting to the current directory would be a nice addition. Using the Shell Script to Get User Input article you’ll see that adding some prompts with read is pretty easy. Next we’ll use some bash if/then/else statements to read over that input to check for blank input and a check to make sure that it is a valid directory, exiting if it is not.

# Get the Current working directory
# Get User Input
echo "Enter Directory to run in [\"$PWD\"]: "
read inputline;
# handle blankline (default)
if [ -z "$inputline" ]; then
# Check to make sure that it is a valid directory
if [ ! -d "$inputline" ]; then
        # Doesn't exist, exit
        echo "Directory $inputline does not exist"
echo "Running in $inputline"
find "$inputline" -iname "*(?)*" | while read i; do echo rm "$i"; done;
echo "Done"

The example above has an echo added in-front of the “rm” statement to stop people from copy and pasting the script and indadvertedly removing files.
The only other difference between last weeks one-liner and this weeks besides all of the wrappers is the “$inputline” in place of the . (current directory.)

Here is the output, ran in my Downloads folder:

bash-3.2$ ./cleanup-downloads
Enter Directory to run in ["/home/linuxblog/"]:
Running in /home/linuxblog/Downloads
rm /home/linuxblog/Downloads/cabinet_child_lock (1).stl
rm /home/linuxblog/Downloads/OpenSCAD-2014.03-x86-64-Installer (1).exe
rm /home/linuxblog/Downloads/PneumaticConnectorCust_3_8 (1).stl
rm /home/linuxblog/Downloads/stamp_20141214-11880-rqxdfd-0 (1).stl
rm /home/linuxblog/Downloads/stamp_20141214-11880-rqxdfd-0 (2).stl

In future articles we’ll add some additional functionality. Adding switches to control deletion (rather than using echo as above.) Adding counting functionality for the number of files to be inspected/deleted or perhaps file comparisons to see if they are the same file and prompting the user to take action such as keeping the latest file, renaming it to the original file name, or keeping both.