Syntax Killer Syntax Killer - 16 days ago 5
Bash Question

How to develop this sort script further

I have a small interactive unix script that takes a terminal command input for a chosen file type and upon receiving such iterates through a large folder of unsorted files on my desktop and pulls files of that chosen selection to a new sorted folder.

i.e. The user types jpg in the command and all jpg files are pulled out of the unsorted folder and into the sorted folder.

It works terrific as it stands, but I would like to develop my script further so that instead of all file types being pushed into a communal sorted folder, I could have jpg files being pushed into a dedicated folderjpg, png files pushed in folderpng and finally all docx files moved into docxfolder.

How can I achieve such in the leanest possible manner assuming that these dedicated folders for the file types mentioned have been created on my desktop.

#!/bin/bash

echo "Good Morning, Please enter your file type name for sorting [ENTER]:"
read extension
mv -v /Users/christopherdorman/desktop/unsorted/*.${extension} /Users/christopherdorman/desktop/sorted/
if [[ $? -eq 0 ]]; then
echo "Good News, Your files have been successfully processed"
fi

Answer

I would write it this way:

read -p "Good Morning, Please enter your file type name for sorting [ENTER]:" extension
if cd /Users/christopherdorman/desktop; then
    destination="folder$extension"
    # ensure the destination folder exists
    mkdir -p "$destination"
    if mv  -v unsorted/*."$extension" "$destination"; then
        echo "Good News, Your files have been successfully processed"
    fi
fi
Comments