Carlos Miranda

File organizer with a Bash Script

March 10, 2025

Recently, I started learning more about terminals and shells. To apply what i’ve learned over the past few days, I decided to create a file organizer using a simple Bash Script. It uses file extensions to sort them in different directories. For example, files like music.mp3 and video.mp4 are organized into the mp3 and mp4 directories, respectively.

What are Terminals and Shells?

A Terminal is a program that allows users to type textual commands and displays the results on the screen. The component responsable for interpreting and executing these commands is known as Shell. Many times, a Shell is also called REPL (Read-Eval-Print Loop), which means:

0. Create a .sh file.

Start by creating a file called file_organizer.sh (or any other name, as long as it has the .sh suffix). This file will contain all the necessary code for organizing files.

To execute the script, you need to grant execution permission using the chmod command:

chmod +x ./file_organizer.sh

1. Get the name of all files in the directory.

First, we need to get the names of all the files in the directory. To do this, we can use a for-loop, passing the path of the target directory as a parameter:

for filepath in path/to/directory/*; do
    echo filepath
done

However, this is not enough; we only need the file names, not the file paths. To do this, we use the basename command, which removes the directory path and extracts only the base name of the files:

filename=$(basename “$filepath”)

2. Create directories based on the extensions.

To create directories and sort all the files, it’s necessary to extract the file extensions:

extension=”${filename##*.}”

The # symbol removes the shortest matching prefix from the beginning of a string that corresponds to the specified pattern. When two ## symbols are used, it removes the longest matching prefix. For example, ${filename##*.} extracts the file extension from $filename, removing everything up to and including the last dot ( . ), and returns only the extension.

Example:

filename=”popcorn.txt”
extension=”${filename##*.}”  # Output: “txt”

To create the directories that will store the files, it’s necessary to combine the directory path with the value of the extension variable.

mkdir “path/to/directory/$extension”

The mkdir command creates a directory; however, an error can occur if you try to create a directory that already exists. To avoid this, it’s necessary to first check if the directory exists. If it does, the directory will not be created:

if [ ! -d “path/to/directory/$extension” ]; then
    mkdir “path/to/directory/$extension”
fi

In the code, the -d flag checks if the specified directory in the path exists and returns true or false. If the directory doesn’t exist, the mkdir command is used to create it.

3. Move the files.

To move each file to its respective directory, we use the mv command:

mv “$filepath” “path/to/directory/$extension”

However, to ensure that only files are moved, it’s necessary to verify if the specified path corresponds to a file using the -f flag:

if [ -f “$filepath” ]; then
    mv “$filepath” “path/to/directory/$extension”
fi

4. Configure user paths.

To allow the user to be able to use the script passing the path of the directory in this way:

./file_organizer.sh path/to/directory/

It is necessary to access the path provided by the user as an argument. This is done through the positional parameter $1, which contains the value of the first argument passed to the script. After this value is assigned to a path variable, it will be used to process the files.

This is the complete code for the script:

#!/bin/bash
path=$1
for filepath in $path/*; do
    filename=$(basename “$filepath”)
    extension=”${filename##*.}”
    if [ ! -d “$path/$extension” ]; then
        mkdir “$path/$extension”
    fi
    if [ -f “$filepath” ]; then
        mv “$filepath” “$path/$extension”
    fi
done

(Optional) 5. Configure script path.

If you wish to access the script from anywhere, it’s necessary to add its path to the .bashrc file. This file is executed automatically when the terminal is initialized and defines environment variables. At the end of the file, add the following line:

export PATH=$PATH:/path/to/the/directory/scripts/

With this, the directory where the script is stored will be added to the PATH. Now, you will be able to execute the script from anywhere on your local machine by simply using the file name.

References

https://stackoverflow.com/questions/35666019/how-does-extension-filename-work-in-bash

https://www.boot.dev/lessons/f9d0dadb-59f8-489b-af77-f6693000d569

https://mlopswithhamza.medium.com/simple-project-organize-your-chaotic-files-with-a-shell-script-08d7829fbd6c