Skip to content

Instantly share code, notes, and snippets.

@miku
Forked from montasaurus/llmc.sh
Created February 28, 2024 12:07
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 miku/b80547e93cb7278ded894e0b66e5f05e to your computer and use it in GitHub Desktop.
Save miku/b80547e93cb7278ded894e0b66e5f05e to your computer and use it in GitHub Desktop.
AI Shell Command Generator
llmc() {
local system_prompt='Output a command that I can run in a ZSH terminal on macOS to accomplish the following task. Try to make the command self-documenting, using the long version of flags where possible. Output the command first enclosed in a "```zsh" codeblock followed by a concise explanation of how it accomplishes it.'
local temp_file=$(mktemp)
local capturing=true
local command_buffer=""
local first_line=true
local cleaned_up=false # Flag to indicate whether cleanup has been run
cleanup() {
# Only run cleanup if it hasn't been done yet
if [[ "$cleaned_up" == false ]]; then
cleaned_up=true # Set the flag to prevent duplicate cleanup
# Check if the temporary file exists before attempting to read from it
if [[ -f "$temp_file" ]]; then
while IFS= read -r line; do
if [[ "$line" == '```zsh' ]]; then
command_buffer=""
first_line=true
elif [[ "$line" == '```' && "$capturing" == true ]]; then
if [[ "$first_line" == true ]]; then
echo -n "$command_buffer" | pbcopy
else
echo -n "${command_buffer//$'\n'/\\n}" | pbcopy
fi
break
elif [[ "$capturing" == true ]]; then
if [[ "$first_line" == false ]]; then
command_buffer+=$'\n'
fi
command_buffer+="$line"
first_line=false
fi
done <"$temp_file"
fi
# Always attempt to remove the temporary file if it exists
[[ -f "$temp_file" ]] && rm "$temp_file"
# Reset the signal trap to the default behavior to clean up resources
trap - SIGINT
fi
}
# Set the trap for cleanup on SIGINT
trap cleanup SIGINT
llm -s "$system_prompt" "$1" | tee >(cat >"$temp_file")
# Ensure cleanup is performed if not already done by trap
cleanup
}

AI Shell Command Generator using LLM

  • Prompts llm to write you a simple shell command with an explanation.
  • Copies the command to your clipboard (even if you cancel generation before the explanation completes).

Usage

llmc 'revert the changes from the last two git commits'

Installation

Install and configure the llm CLI tool. Add the llmc function to your .zshrc.

Caveats

  • Prompts specifically for a ZSH command on a macOS machine
  • Obviously, be careful running commands you don't understand & use at your own risk.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment