Skip to content

Instantly share code, notes, and snippets.

@simgunz
Created November 26, 2023 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simgunz/893cfe99971e2813e01655db82cc837d to your computer and use it in GitHub Desktop.
Save simgunz/893cfe99971e2813e01655db82cc837d to your computer and use it in GitHub Desktop.
'al' function to list aliases in a menu
#!/bin/zsh
##? al - list my aliases
function al() {
local zalias_file="$HOME/.zsh/zalias"
local IFS=$'\n' # Change the field separator to newline
local categories=() # Array to store categories
local formatted_aliases=() # Array to store formatted alias strings
local selected_category=""
local choice
# Read categories
while read -r line; do
if [[ $line == "##"* ]]; then
categories+=("${line##\#\# }")
fi
done < "$zalias_file"
# Display categories and prompt for choice
echo "Select a category:"
select category in "${categories[@]}"; do
if [[ -n $category ]]; then
selected_category=$category
break
else
echo "Invalid choice. Please try again."
fi
done
# Clear formatted_aliases array
formatted_aliases=()
# Read aliases for selected category
local in_category=false
while read -r line; do
if [[ $line == "## $selected_category" ]]; then
in_category=true
continue
fi
if [[ $in_category == true && $line == "##"* ]]; then
break
fi
if [[ $in_category == true && $line == alias* ]]; then
local alias_name=$(echo "$line" | cut -d'=' -f1 | awk '{print $2}')
local description=$(echo "$line" | awk -F'#' '{print $2}' | xargs)
local first_char=$(echo "${description:0:1}" | tr '[:upper:]' '[:lower:]')
local rest=${description:1}
description="$first_char$rest"
formatted_aliases+=("$alias_name: $description")
fi
done < "$zalias_file"
# Display aliases and prompt for choice
echo "Select an alias from '$selected_category':"
select choice in "${formatted_aliases[@]}"; do
if [[ -n $choice ]]; then
# Extract and print the command from the choice
exact_match_alias=$(echo "$choice" | cut -d':' -f1)
# Extract the exact command from the file
grep "^alias $exact_match_alias=" "$zalias_file" | cut -d'=' -f2- | awk -F'#' '{print $1}'
break
else
echo "Invalid choice. Please try again."
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment