Skip to content

Instantly share code, notes, and snippets.

@gwpl
Last active March 7, 2025 20:33
Show Gist options
  • Save gwpl/a5e47034029bcb37de5b13f64108fc80 to your computer and use it in GitHub Desktop.
Save gwpl/a5e47034029bcb37de5b13f64108fc80 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Bash completion for the "ollama" CLI. Requires jq and curl.
#
# Published:
# * https://github.com/CLIAI/handy_scripts/blob/main/bash_completion/etc/bash_completion.d/ollama
# * https://gist.github.com/gwpl/a5e47034029bcb37de5b13f64108fc80/
# Cache settings
_OLLAMA_MODEL_TTL=300
_OLLAMA_MODELS_TIMESTAMP=0
_OLLAMA_MODELS=""
# Fetch models from Ollama server, caching results
_ollama_fetch_models() {
local now
now=$(date +%s)
if [ $(( now - _OLLAMA_MODELS_TIMESTAMP )) -gt $_OLLAMA_MODEL_TTL ]; then
_OLLAMA_MODELS=$(
curl -s http://localhost:11434/api/tags \
| jq -r '.models[].name'
)
_OLLAMA_MODELS_TIMESTAMP=$now
fi
}
# Main completion function
_ollama() {
local cur prev
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
case "${prev}" in
run)
# Get fresh models from Ollama
_ollama_fetch_models
# Filter models by whatever the user has typed so far (case-insensitive)
# and feed them into compgen so they appear as completions.
local filtered
filtered=$(echo "$_OLLAMA_MODELS" | grep -i "$cur")
COMPREPLY=( $(compgen -W "${filtered}" -- "$cur") )
return 0
;;
esac
# Default commands
COMPREPLY=( $(compgen -W "serve create show run pull push list ps cp rm help" -- "$cur") )
}
# Register the completion function
complete -F _ollama ollama

Implementing Bash Autocomplete for Ollama

source: https://www.perplexity.ai/search/did-people-make-for-ollama-bas-3RErncU0QcqHwaS64ukerw

You can implement bash autocompletion for Ollama model names by creating a custom bash completion script. Based on the search results, there's already a well-developed solution available that provides exactly this functionality.

Installation Steps

  1. Create a new file for the Ollama completion script:
sudo nano /etc/bash_completion.d/ollama

Or create it in your home directory:

nano ~/.ollama-completion.sh
  1. Copy the completion script from the GitHub issue[1] into this file (script details below).

  2. If you placed it in your home directory, add this line to your .bashrc file:

source ~/.ollama-completion.sh
  1. Install required dependencies:
sudo apt install jq curl
  1. Restart your terminal or source your bashrc file:
source ~/.bashrc
@gwpl
Copy link
Author

gwpl commented Mar 7, 2025

Trying to merge into Ollama mainstream repo: ollama/ollama#9585

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