Home AI SkillsHow to Call an LLM API from Bash: Automate Reports with curl and jq

How to Call an LLM API from Bash: Automate Reports with curl and jq

by Knowledge Base Linux
How to Call an LLM API — How to Call an LLM API from Bash: Automate Reports with curl and jq

Shell scripts are the glue of Linux administration, but they are bad at understanding text. The moment you can call an LLM API from Bash, your scripts gain a brain: they can summarize a status report, classify an alert, or draft an incident note before sending it to your chat channel. In this guide you will use curl and jq to call an LLM API from Bash, handle the JSON response safely, and build a practical daily server report script.

How an LLM API from Bash Actually Works – How to Call an LLM API

Every major LLM provider exposes a simple HTTPS endpoint: you POST a JSON document with your prompt, and you get JSON back with the model’s answer. Bash is perfectly capable of speaking this protocol because curl handles HTTPS and jq handles JSON. The pattern is always the same:

  1. Build the request JSON with jq (never with string concatenation).
  2. POST it with curl, passing your API key in a header.
  3. Extract the answer text with jq -r.
  4. Use the answer in the rest of your script: a file, an email, a webhook.

This works with the OpenAI API, any OpenAI-compatible endpoint, and even a local Ollama server, which also exposes an OpenAI-compatible API on port 11434.

Prerequisites – How to Call an LLM API

  • A Linux server with curl and jq installed.
  • An API key from an LLM provider, or a local Ollama instance (see our Ollama self-hosting guide).
  • Basic Bash knowledge: variables, functions and exit codes.

Step 1: Store Your API Key Safely

Never hard-code a key inside a script that lives in Git. Store it in a root-only file or an environment variable:

sudo install -m 600 /dev/null /etc/llm-api-key
echo "sk-your-key-here" | sudo tee /etc/llm-api-key > /dev/null
export OPENAI_API_KEY=$(sudo cat /etc/llm-api-key)

Step 2: Make Your First LLM API Call from Bash

The chat completions endpoint accepts a list of messages. Build it with jq so any quotes in your prompt are escaped correctly:

PROMPT="Explain in one sentence why a Linux server load average of 40 on 4 CPUs is a problem."
BODY=$(jq -n --arg p "$PROMPT" '{
  model: "gpt-4o-mini",
  messages: [
    {role: "system", content: "You are a concise Linux sysadmin assistant."},
    {role: "user", content: $p}
  ],
  temperature: 0.2
}')
curl -s https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$BODY" | jq -r '.choices[0].message.content'

Using a local Ollama model instead? Only the base URL and model name change:

curl -s http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d "$BODY" | jq -r '.choices[0].message.content'
# and in BODY use: model: "llama3.1:8b"

Step 3: Wrap the LLM API in a Bash Function

A reusable function keeps every script in your toolbox consistent:

#!/usr/bin/env bash
ask_llm() {
  local prompt="$1"
  local body
  body=$(jq -n --arg p "$prompt" '{
    model: "gpt-4o-mini",
    messages: [{role: "user", content: $p}],
    temperature: 0.2
  }')
  curl -s --max-time 60 https://api.openai.com/v1/chat/completions \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$body" | jq -r '.choices[0].message.content // empty'
}
SUMMARY=$(ask_llm "Summarize this server status in two sentences: $(uptime; df -h / | tail -1; free -h | head -2)")
echo "$SUMMARY"

The // empty fallback matters: if the API returns an error object instead of an answer, your script gets an empty string it can test for, instead of the literal text “null”.

LLM API from Bash automation workflow illustration

Step 4: Build a Daily Report with an LLM API from Bash

Now combine data collection, summarization and delivery into a cron-ready script:

#!/usr/bin/env bash
set -euo pipefail
export OPENAI_API_KEY=$(cat /etc/llm-api-key)
REPORT=$(mktemp)
{
  echo "Host: $(hostname)  Date: $(date)"
  echo "Uptime: $(uptime -p)"
  echo "Failed units:"; systemctl --failed --no-legend || true
  echo "Disk:"; df -h / /var 2>/dev/null | tail -n +2
  echo "Top memory processes:"; ps aux --sort=-%mem | head -6
} > "$REPORT"
TEXT=$(ask_llm "Write a short daily report for a sysadmin from this data. Flag anything abnormal in the first line. Data: $(cat "$REPORT")")
echo "$TEXT" | mail -s "Daily report: $(hostname)" [email protected]
rm -f "$REPORT"

Schedule it with crontab -e at 07:00 and your inbox gets a readable summary instead of raw command output. This is the same pattern used by bigger AI agent automation setups, just without any framework.

Troubleshooting

401 Unauthorized. The key is wrong, revoked, or the header is missing. Test the key alone with a minimal request before debugging the script.

jq: parse error. The API returned an error page or empty body (often a 429 rate limit or a timeout). Save the raw response to a file and inspect it: curl ... -o /tmp/resp.json; cat /tmp/resp.json.

The answer is cut off. Raise max_tokens in the request body, or shorten the prompt.

The script hangs. Always set --max-time on curl so a slow API cannot stall your cron jobs forever.

Conclusion

Calling an LLM API from Bash takes three tools you already have — curl, jq and a text prompt — and unlocks summarization, classification and drafting inside any script. Keep keys out of your code, build JSON with jq, add timeouts, and check for empty answers. Once this pattern is in your toolbox, every monitoring script, backup job and alert pipeline you own can explain itself in plain language.

You may also like

KbLinux

Typically replies within a day

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