Bash Programming

Bash script: Automated File Organizer Script


#!/bin/bash

# Define the directory to organize
directory_to_organize="/path/to/directory"

# Create folders for each file type if they do not already exist
mkdir -p $directory_to_organize/images
mkdir -p $directory_to_organize/documents
mkdir -p $directory_to_organize/audio
mkdir -p $directory_to_organize/videos
mkdir -p $directory_to_organize/others

# Move files to their respective folders based on their type or extension
for file in $directory_to_organize/*
do
if [ -f "$file" ]
then
if file --mime-type "$file" | grep -q "image"
then
mv "$file" $directory_to_organize/images
elif file --mime-type "$file" | grep -q "text"
then
mv "$file" $directory_to_organize/documents
elif file --mime-type "$file" | grep -q "audio"
then
mv "$file" $directory_to_organize/audio
elif file --mime-type "$file" | grep -q "video"
then
mv "$file" $directory_to_organize/videos
else
mv "$file" $directory_to_organize/others
fi
fi
done

This bash script automates the process of organizing files in a directory based on their type or extension into designated folders.

Explanation:
1. The script starts by defining the directory that needs to be organized.
2. It then creates separate folders within the directory for images, documents, audio files, video files, and any other files that do not fall into these categories.
3. The script iterates through each file in the specified directory.
4. For each file, it checks if it is a regular file using the `-f` flag.
5. It then uses the `file –mime-type` command to determine the type of the file based on its MIME type.
6. Depending on the file type identified, the script moves the file to the corresponding folder (images, documents, audio, videos) using the `mv` command.
7. If the file type does not match any of the predefined categories, the file is moved to the “others” folder.
8. The script effectively organizes files based on their types or extensions, making it easier to manage and locate specific types of files within the directory.

This script is a useful automation tool for organizing files and can be customized further based on specific file types or categories.