Last active
January 29, 2025 02:16
-
-
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
fzf
batcat
.{} --help | batcat
.