Bash script for cleaning Visual Studio Project build directories (e.g.: bin/, obj/, etc.) from a particular path, recursively.

#!/usr/bin/env bash

#
# Delete dotnet build dirs and files ('bin', 'obj', etc) recursively, starting
# from the current working directory.
#
# Author: Jon LaBelle
# https://jonlabelle.com/snippets/view/shell/clean-visual-studio-project-build-files-sh
# January 25, 2019
#

set -e
set -o pipefail

readonly SCRIPT_NAME=$(basename "${0}")

IS_DRYRUN=true

show_usage() {
    echo "Usage: ${SCRIPT_NAME} [options]"
    echo
    echo "Delete dotnet build dirs and files ('bin', 'obj', etc) recursively, "
    echo "starting from the current working directory."
    echo
    echo "Options:"
    echo
    echo "  -n, --dry-run    preview without delete."
    echo "  -h, --help       show this help message and exit."
    echo
}

heading() { printf "→ %s\\n" "$@"; }
warn() { printf "$(tput setaf 3)%s$(tput sgr0)\\n" "$@"; }
success() { printf "$(tput setaf 76)✔ %s$(tput sgr0)\\n" "$@"; }

clean_dirs_recursively() {
    heading "Cleaning '${1}' dirs..."
    find . -name "${1}" -type d -print | xargs -0 echo
    if [ "$IS_DRYRUN" = "false" ]; then
        # shellcheck disable=SC2086,SC2048
        find . -name ${1} -type d -print0 | xargs -0 rm -rf
    fi
}

clean_files_recursively() {
    heading "Cleaning '${1}' files..."
    find . -name "${1}" -type f -print | xargs -0 echo
    if [ "$IS_DRYRUN" = "false" ]; then
        # shellcheck disable=SC2086,SC2048
        find . -name ${1} -type f -print0 | xargs -0 rm -rf
    fi
}

main() {
	echo
    if [[ "$1" = "-h" || "$1" = "--help" || "$1" = "help" || "$1" = "-v" || "$1" = "--version"  ]]; then
        show_usage
        exit 0
    fi

    if [[ "$1" = "-n" || "$1" = "--dry-run" ]]; then
        IS_DRYRUN=true
        warn "Dry-run only... files will NOT be deleted."
        echo
    else
        IS_DRYRUN=false
    fi

    #
    # clean vs dirs:
    clean_dirs_recursively 'bin'
    clean_dirs_recursively 'obj'

    # other dotnet ide user setttings dirs (visual studio, ryder, vscode)
    clean_dirs_recursively '.vs'
    clean_dirs_recursively '.idea'
    clean_dirs_recursively '.vscode'

    # careful with this one... pass '--dry-run' to preview without delete
    clean_dirs_recursively 'packages'

    #
    # legacy visual studio user settings files:
    clean_files_recursively '*.suo'

    #
    # vs and mono-develop user prefs
    clean_files_recursively '*.user'
    clean_files_recursively '*.userprefs'

    #
    # stylecop cache files:
    clean_files_recursively 'StyleCop.Cache'

    #
    # macOS files:
    clean_files_recursively '.DS_Store'

    echo
    success "Finished."
    echo
    exit 0
}

# shellcheck disable=SC2086,SC2048
main $*