#!/bin/bash set -euo pipefail KEY_FILE="$HOME/.openai_api_key" MODEL="gpt-4.1-nano" MAX_TOKENS=100 # Display usage information show_help() { cat < Any argument starting with '-' will be sent directly as a prompt instead of asking to output a bash command. Environment Variables: OPENAI_API_KEY Required. If not set, the script will prompt once and save to ~/.openai_api_key. VERBOSE=true Optional. Enables debug output. Examples: $(basename "$0") "list all files in /tmp modified in the last 24 hours" $(basename "$0") "restart nginx service if it's not running" $(basename "$0") -q "Explain the ls command options" # sends directly to API EOF } # Exit with help if no arguments or help flag is provided if [[ $# -eq 0 || "$1" =~ ^-h|--help$ ]]; then show_help exit 0 fi # Load API key from file if not already set if [[ -z "${OPENAI_API_KEY:-}" && -f "$KEY_FILE" ]]; then OPENAI_API_KEY=$(<"$KEY_FILE") fi # Prompt for API key if still not set if [[ -z "${OPENAI_API_KEY:-}" ]]; then read -s -p "Paste OpenAI API key: " OPENAI_API_KEY echo [[ -z "$OPENAI_API_KEY" ]] && echo "API key required" && exit 1 echo "$OPENAI_API_KEY" > "$KEY_FILE" chmod 600 "$KEY_FILE" fi # Determine prompt and whether to skip command execution if [[ "${1:0:1}" == "-" ]]; then prompt="$*" skip_run=true else prompt="Only output the bash command to: $*" skip_run=false fi # Verbose output if [[ "${VERBOSE:-}" == true ]]; then echo "[Verbose] Prompt: $prompt" fi # Generate JSON payload json_payload=$(jq -n \ --arg model "$MODEL" \ --arg prompt "$prompt" \ --argjson max_tokens "$MAX_TOKENS" \ '{ model: $model, messages: [{role:"user", content:$prompt}], temperature:0, max_tokens:$max_tokens }' ) # Send request to OpenAI API response=$(curl -sS https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d "$json_payload" ) # Extract command from API response command=$(echo "$response" | jq -r '.choices[0].message.content // empty' | sed '/^```/d') [[ -z "$command" ]] && echo "Failed to get command" && exit 1 echo -e "\nSuggested\n$command" # Optionally run command if [[ "$skip_run" != true ]]; then read -p "Run this command? (y/n): " confirm if [[ "$confirm" =~ ^[Yy]$ ]]; then eval "$command" else echo "Cancelled." fi fi