feat: updates, docs, license fixes, new helpers

This commit is contained in:
2025-02-12 01:05:37 +02:00
parent cdd68748e0
commit 88efedf26b
25 changed files with 1559 additions and 355 deletions

View File

@@ -1,33 +1,50 @@
#!/usr/bin/env bash
#
# Add a directory to the front of the PATH if it exists and is not already there
# Usage: x-path-prepend <dir>
# Optimized script to batch prepend directories to PATH.
# For each given directory, it removes all duplicate occurrences from PATH
# and then prepends it. Directories that do not exist are skipped.
#
# Usage: x-path-prepend <directory1> [<directory2> ...]
#
# Enable verbose output by setting the environment variable VERBOSE=1.
#
# Author: Ismo Vuorinen <https://github.com/ivuorinen> 2024
# License: MIT
# Set verbosity with VERBOSE=1
VERBOSE="${VERBOSE:-0}"
# Function to print messages if VERBOSE is enabled
# $1 - message (string)
msg()
{
[[ "$VERBOSE" -eq 1 ]] && echo "$1"
# Ensure that at least one argument is provided.
[ "$#" -lt 1 ] && {
echo "Usage: $0 <directory> [<directory> ...]"
exit 1
}
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <dir>"
exit 1
fi
# Save the arguments in an array.
dirs=("$@")
dir="$1"
# Process the directories in reverse order so that the first argument ends up leftmost in PATH.
for ((idx = ${#dirs[@]} - 1; idx >= 0; idx--)); do
dir="${dirs[idx]}"
if [ ! -d "$dir" ]; then
msg "(?) Directory $dir does not exist"
exit 0
fi
# Check if the specified directory exists.
if [ ! -d "$dir" ]; then
[ "$VERBOSE" -eq 1 ] && echo "(?) Directory '$dir' does not exist. Skipping."
continue
fi
if echo "$PATH" | grep -qE "(^|:)$dir($|:)"; then
msg "(!) Directory $dir is already in PATH"
else
# Remove all duplicate occurrences of the directory from PATH using built-in string operations.
case ":$PATH:" in
*":$dir:"*)
PATH=":${PATH}:"
PATH="${PATH//:$dir:/:}"
PATH="${PATH#:}"
PATH="${PATH%:}"
[ "$VERBOSE" -eq 1 ] && echo "Removed duplicate occurrences of '$dir' from PATH."
;;
*) ;;
esac
# Prepend the directory to PATH.
export PATH="$dir${PATH:+":$PATH"}"
msg "(!) Directory $dir has been added to the front of PATH"
fi
[ "$VERBOSE" -eq 1 ] && echo "Prepended '$dir' to PATH."
done