tree

research scripts

Written in 2019. Prints the folder structure tree based on the provided nesting level. Outlines folders and files matching the provided string.

#!/bin/bash

initial_max_depth=2
matching_string=""
matching_string_provided="false"

display_branch()
{
    for D in $(ls $1); do
        if [[ -d "$1/$D" ]]; then

            # Display folders
            if [[ $D == *$matching_string* && $matching_string_provided == "true" ]]; then
                echo -e "\e[37m$2\e[91m$D\e[0m"
            elif [[ $matching_string_provided == "false" ]]; then
                echo -e "\e[37m$2\e[96m$D"
            fi

            # Recursive display branch
            if [ $3 -gt 0 ]; then
                lag="$2$D/"
                # lag="$2----|"
                max_depth="$(($3-1))"
                display_branch "$1/$D" $lag $max_depth
            fi
        else
            # Display file
            if [[ $D == *$matching_string* && $matching_string_provided == "true" ]]; then
                echo -e "\e[37m$2\e[93m$D"
            fi
        fi
    done
}

if [[ $1 == "-h" ]]; then
    # Show helps
    echo -e """
___________________________________________________________________
Michele Salvucci | @2019 | Bash
-------------------------------------------------------------------
Prints the folder structure tree based on the provided nesting level.
Outlines folders and files matching the provided string.
-------------------------------------------------------------------
Args:
    -md|--max_depth     The level of folder structure nesting.

    -ms|--matching_string   If provided, every folder/file matching this
                            string is outlined, others are not shown.
                            Matching folders are lighted red while files
                            are yellow.
___________________________________________________________________
    """
else
    # Parse arguments
    for arg in "$@"
    do
        case $arg in
            -md|--max_depth)
                initial_max_depth=$2
                ;;
            -ms|--matching_string)
                matching_string=$2
                matching_string_provided="true"
                ;;
        esac
        shift
    done

    # Launch tree display
    display_branch "." "|" $initial_max_depth
    echo -e "\e[39m"
fi

Previous Post Next Post