Skip to content

Instantly share code, notes, and snippets.

@marcbelmont
Last active January 29, 2025 02:16
Show Gist options
  • Save marcbelmont/99915d8b40e389b674aff697c73ae5bc to your computer and use it in GitHub Desktop.
Save marcbelmont/99915d8b40e389b674aff697c73ae5bc to your computer and use it in GitHub Desktop.
This Bash script acts as an interactive command launcher using `fzf`, a command-line fuzzy finder. Let's break down its functionality and features:
#!/bin/bash
set -e
history_file="$HOME/.fzf/history"
commands_file="$HOME/.fzf/commands"
cache_expiration=43200 # 12 hours
# Function to regenerate the commands cache if it's missing or outdated
regenerate_commands_cache() {
if [[ ! -f "$commands_file" || $(( $(date +%s) - $(stat -c %Y "$commands_file") )) -gt "$cache_expiration" ]]; then
compgen -c | sort -u > "$commands_file"
fi
}
# Function to handle command selection and execution
select_and_execute_command() {
selected=$(
echo -e "$(cat $history_file|sort)\\n$(cat $commands_file)" |
fzf +s --reverse --prompt="🚀 " \
--preview-window=down,2 \
--preview 'file $(type -P {}); echo -n "Modified: "; stat -c %y $(type -P {})' \
--preview-label="Help: ctrl-h, Inspect: ctrl-i, Clear Cache: ctrl-e" \
--bind 'ctrl-i:execute(batcat --color=always $(type -P {}))' \
--bind "ctrl-h:execute({} --help|batcat --color=always)" \
--bind "ctrl-e:execute(rm "$commands_file")+abort" \
--bind "enter:accept-or-print-query"
)
if [[ -n "$selected" ]]; then
if ! grep -q "^$selected$" "$commands_file"; then
eval "$selected"
else
nohup "$selected" >/dev/null 2>&1 &
fi
manage_history "$selected"
else
echo "No command selected."
fi
}
# Function to manage command history
manage_history() {
local selected_command="$1"
sed -i "/$selected_command/d" "$history_file"
echo "$selected_command" >> "$history_file"
tail -n 20 "$history_file" > "$history_file.tmp" && mv "$history_file.tmp" "$history_file"
}
# Main script execution
regenerate_commands_cache
select_and_execute_command
@coderofsalvation
Copy link

I've added this so it lists my highlevel command-wrappers in ~/bin first:

5 # Generate a list of available commands using compgen
6 commands=$(ls ~/bin; compgen -c | sort -u)

@marcbelmont
Copy link
Author

marcbelmont commented Jan 29, 2025

image

The script provides a user-friendly interface to search for and execute commands, combining recently used commands (history) with a comprehensive list of available commands on the system. It employs caching to improve performance and offers features like previewing command information and help messages.

  • Command Selection and Execution with fzf
  • Command History and Cache
  • Inspect the selected command using batcat.
  • Display the help message of the selected command using {} --help | batcat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment