Home AI SkillsShellGPT: Bring AI Assistance to Your Linux Terminal

ShellGPT: Bring AI Assistance to Your Linux Terminal

by Knowledge Base Linux
ShellGPT AI assistant helping inside a Linux terminal window, technical illustration

Your Terminal, Now with an AI Co-Pilot

Every sysadmin knows the moment: you need to find all log files older than 30 days, excluding a directory, and delete them safely — and you pause, because the exact syntax for that one-liner never quite sticks. You could open a browser, search, and copy-paste a command you only half understand. Or you could ask your terminal directly. ShellGPT (the sgpt command, from the shell-gpt Python package) brings an AI assistant into your Linux shell: it answers questions, generates shell commands from plain English, writes code snippets, and even holds an interactive chat — all without leaving the terminal.

Natural language questions converted into terminal commands by ShellGPT, technical diagram

ShellGPT is not a magic autocomplete. It is an OpenAI-powered command-line client that sends your prompts to a language model and returns text you can execute, save, or pipe. For routine sysadmin work — crafting tricky find filters, translating a task description into an rsync command, or getting a one-line explanation of a flag — it is genuinely fast. In this guide you will install ShellGPT on Linux, set up your API key, use sgpt --shell, sgpt --code, and sgpt --chat with realistic examples, wire it into your shell, understand the cost and privacy trade-offs, and fix common setup problems.

Prerequisites

  • A Linux machine with Python 3.8 or newer (python3 --version) and pip3.
  • An OpenAI API key — create one at platform.openai.com under API keys. API usage is billed, so set a spending limit in the OpenAI dashboard first.
  • Basic comfort with the terminal. If you want a gentler on-ramp to AI-assisted typing, our guide to Inshellisense AI command completion is a good warm-up, and if you prefer calling APIs directly, see using LLM APIs from bash with curl and jq.

Step 1: Install ShellGPT on Linux

ShellGPT ships as the shell-gpt PyPI package. On recent distributions (Ubuntu 23.04+, Debian 12+, Kali) system-wide pip install is blocked as an externally-managed environment, so use pipx, which gives the tool its own isolated virtualenv:

sudo apt update && sudo apt install -y pipx
pipx ensurepath
pipx install shell-gpt
sgpt --version

Open a new terminal (or run exec "$SHELL" -l) after pipx ensurepath so your PATH picks up the new binary. If sgpt is not found after that, that PATH update is the usual cause. On older systems where plain pip is still allowed, pip3 install --user shell-gpt works as well.

Step 2: Configure Your OpenAI API Key

The first time you run sgpt with any prompt, it asks for your API key interactively and stores it in its config file. The safer, scriptable route is the environment variable, which keeps the key out of the config on shared machines:

export OPENAI_API_KEY="sk-your-key-here"

Add that line to ~/.bashrc (or ~/.zshrc) so it persists — but note that storing a key in a dotfile is still a secret-management compromise. For production-adjacent machines, prefer loading it from a password manager or a secrets service at session start rather than hard-coding it. Never commit ~/.bashrc or your ShellGPT config to version control with a live key inside.

You can also pin a model. ShellGPT defaults to a recent GPT model; to use a specific one, set the model in the config or pass it per-call. Check sgpt --help for the current options on your installed version, since flags evolve between releases.

Step 3: Generate Shell Commands with sgpt –shell

This is the headline feature. Describe what you want in plain English, and ShellGPT returns a shell command. By default it shows you the command and asks whether to execute it, describe it, or abort:

sgpt --shell "find all .log files under /var/log older than 30 days and delete them, but skip the nginx directory"

Typical output looks like a review prompt before anything runs:

find /var/log -name "*.log" -type f -mtime +30 -not -path "*/nginx/*" -delete
[E] Execute, [D] Describe, [A] Abort

A few realistic sysadmin examples:

sgpt --shell "show the 10 largest directories in /var with human readable sizes, sorted"
sgpt --shell "list listening TCP ports and the process names that own them"
sgpt --shell "create a tarball of /etc/nginx with today's date in the filename, gzip compressed"

To skip the confirmation and get just the command for scripting, add --no-interaction (or the short form shown in sgpt --help on your version):

sgpt --shell --no-interaction "count unique IP addresses in /var/log/nginx/access.log"

Safety rule: always choose Describe ([D]) when you don’t fully understand the generated command. The model can suggest destructive operations — a wrong rm or a find ... -delete pointed at the wrong tree runs with your privileges. Verify every flag against the man page before executing anything that deletes, overwrites, or restarts services.

Step 4: Generate Code Snippets with sgpt –code

The --code flag strips explanations and returns code only, which is ideal for redirecting straight into a file:

sgpt --code "bash function that checks if a systemd service is active and restarts it if not"
sgpt --code "python script that parses /var/log/auth.log and counts failed SSH logins per IP" > count_logins.py

Combine both modes in one workflow — generate the code, then pipe a quick sanity question:

sgpt --code "awk one-liner to extract 5xx status codes from an nginx access log" > count_5xx.sh
sgpt "what does each part of this awk script do" < count_5xx.sh

Because --code returns nothing but code, it slots neatly into existing automation: generate a draft, review it with your own eyes, test it in a sandbox, and only then promote it to a script you schedule with cron.

Step 5: Chat and Ask Questions with sgpt –chat

For open-ended questions and multi-turn troubleshooting, use chat mode:

sgpt --chat syslog "my disk is full but du shows only 20GB used on a 100GB partition, what should I check"
sgpt --chat devops "explain the difference between docker stop and docker kill"

The first argument after --chat is a session name, so you can return to the same conversation later and keep context. Plain one-shot questions need no flag at all:

sgpt "explain what the rsync --delete flag does and when it is dangerous"

Chat mode is the fastest way to get a plain-English explanation of a config option or an error message without leaving the terminal — paste the error, ask what it means, and follow up in the same session.

Step 6: Shell Integration for a Smoother Workflow

ShellGPT ships shell integration that adds handy bindings to your interactive shell. To set it up, run the integration install command and follow its instructions for your shell (bash, zsh, or fish):

sgpt --install-integration

After a shell restart, you can type a natural-language request right at the prompt, hit the bound key (by default Ctrl+\\ in bash/zsh), and ShellGPT replaces it with the generated command inline. A couple of small aliases round out the experience:

alias s="sgpt --shell --no-interaction"
alias c="sgpt --code"

To reduce friction further, set a default model or shorten the default temperature in ShellGPT’s config file (~/.config/shell_gpt/.sgptrc), so everyday queries stay fast and deterministic.

Cost, Privacy, and Model Considerations

ShellGPT sends every prompt to OpenAI’s API, so two things matter. Cost: each call consumes tokens on your billed account. A handful of daily queries costs pennies, but avoid piping multi-megabyte log files into prompts — trim with head, grep, or tail first, and use cheaper models for trivial questions. Privacy: prompts leave your machine. Never include customer names, internal hostnames, IP ranges, credentials, or captured log data in a prompt. Treat ShellGPT like asking a stranger: useful for generic how-to knowledge, unsafe for anything confidential.

If you need an offline alternative, ShellGPT supports OpenAI-compatible local backends — run a model through Ollama and point ShellGPT at it — at the cost of some answer quality versus hosted models. For details on the project’s full option set, see the official repository at TheR1D/shell_gpt on GitHub.

Troubleshooting ShellGPT

sgpt: command not found after install

Almost always a PATH problem: pipx ensurepath requires a new login shell. Run exec "$SHELL" -l, then check which sgpt. With pip3 --user installs, confirm ~/.local/bin is on your PATH.

Authentication errors / invalid API key

Check that OPENAI_API_KEY is exported in the current shell (echo "${OPENAI_API_KEY:0:5}" — only the prefix, never the full key) and that the key still exists in the OpenAI dashboard. Keys can be revoked; regenerate if in doubt.

Requests hang or time out

Verify outbound HTTPS connectivity to api.openai.com (curl -sI https://api.openai.com). Corporate proxies and strict egress firewalls are common culprits; export https_proxy/http_proxy as needed.

Rate limit errors

You’ve hit your tier’s requests-per-minute cap. Slow down, or check whether the dashboard offers a higher tier. Batch scripting hundreds of calls per minute is a fast way to meet the limit.

Flags differ from the docs

ShellGPT evolves quickly; option names and shorthand change between releases. Your installed copy is the authority: run sgpt --help and match the syntax you see there.

Conclusion

ShellGPT turns your Linux terminal into a conversation with an AI that speaks bash. Install it with pipx install shell-gpt, set OPENAI_API_KEY, and you get three powerful habits for the price of one tool: sgpt --shell for turning task descriptions into reviewable commands, sgpt --code for generating script drafts you can redirect into files, and sgpt --chat for multi-turn troubleshooting. Keep the safety discipline front and center — describe before you execute, verify flags in the man page, and keep secrets and sensitive data out of prompts — and it becomes a genuinely useful co-pilot for day-to-day Linux administration.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.