AI

Automating Retrieval-Augmented Generation (RAG) Pipelines with Bash

AI15 min read

By Aradhya Chaudhary

On this page
Monitors and a tablet showing workflow software, with the words Automation with RAG, Windows and Linux

You can run a whole retrieval-augmented generation (RAG) pipeline from the terminal with Bash. Shell scripts download and clean text with wget, sed and awk, sentence-transformers turns the text into embeddings, FAISS finds the passages closest to a question, and the OpenAI API or a local llama.cpp model writes the answer from them. The commands were written and run on Arch Linux in March 2025, and the screenshots come from those runs. Several scripts are templates that still need parts filled in; the note under each one says which. To run the model on your own hardware, start with our guide to self-hosting LLMs.

What is Retrieval-Augmented Generation (RAG) ?

Retrieval-Augmented Generation (RAG) is a cutting-edge workflow that enhances Large Language Models (LLMs) by integrating external knowledge during runtime. Unlike traditional language models, which rely solely on pre-trained data (often outdated or limited), RAG dynamically retrieves relevant documents from a knowledge base—such as vector databases, document repositories, or APIs—to supplement its responses.

How does RAG work?

  1. Retrieval : A query is sent to a retrieval system (e.g., FAISS, Chroma, Milvus, or Elasticsearch) to fetch relevant contextual documents.
  2. Augmentation: The retrieved documents are added as additional input to the generative model.
  3. Generation: A language model (like GPT, LLaMA, or Mistral) generates an answer using both the query and retrieved information.

Why Automate RAG Workflows ?

Pipelines help us define the flow of automated data into new insights, this can include ETL Pipelines, RAG Pipelines, etc. in multiple repetitive steps such as :

  • Data Preprocessing and Embedding of documents
  • Running the retrieval queries
  • Handling API Calls to generative AI models
  • Formating responses
  • Monitoring and Debugging

These above given steps while manually executed takes more effort and are time consuming, Automation helps in :

  • Reducing human effort
  • Increasing speed and scalability
  • Improving readability

Advantages of Implementing Bash Scripting for RAG Automation

  • Lightweight & Efficient
  • Seamless Integration with CLI Tools
  • Easy Scheduling & Background Execution
  • Secure & Customizable

Prerequisites

Basics of Bash Scripting

  • Familiarity with Bash Scripting ( Loops, Variables, Terminal, Exception Handling, etc )
  • Understanding of core concepts of RAG pipelines or system.

Required Tools and Dependencies

The commands are written for Arch Linux. They rely on Bash, pacman and Linux paths, so on Windows 10 or 11 run them inside WSL (Windows Subsystem for Linux) and use your distro’s package manager in place of pacman.

A. Essential Linux Utilities : For fetching data from web , processing and cleaning data and for handling JSON data.

text
wget, curl, grep, awk, sed, jq

B. AI & ML Dependencies :

  • Python ( as a overall base language )
  • LLM integration ( Open AI GPT, LLaMA, Mistral )
  • Pip and Virtualenv ( To manage dependencies )
  • Vector Databases ( FAISS, Chroma, Milvus )

C. Arch Linux setup :

Go to your start or development menu then click terminal

Empty Konsole terminal window on an Arch Linux KDE desktop

Type the following command to install packages using pacman :

bash
sudo pacman -S wget curl jq python

Konsole running sudo pacman -S wget curl jq python and asking to proceed with the installation

After running these steps the package will start installing and you must receive the outputs like this :

pacman output after installing wget, curl, jq, oniguruma and python

(Optional) Use AUR for additional tools like chromadb or faiss

Setting up the RAG system on Arch Linux

Installing and Configuring Retrieval System

The retrieval side stores your documents as vectors and searches them. This guide installs two vector stores in a Python virtual environment: FAISS (Facebook AI Similarity Search) and ChromaDB.

Installing FAISS on Arch Linux via Terminal :

bash
pip install faiss-cpu  # For CPU
pip install faiss-gpu  # For GPU acceleration (if available)

You might get error due to externally-managed-environment which may look like :

pip install faiss-cpu failing with an externally-managed-environment error on Arch Linux

The error suggests pacman, but Arch’s official repositories have no python-faiss or python-chromadb package (python-chromadb is in the AUR), so these commands fail too:

bash
sudo pacman -S python-faiss  
sudo pacman -S python-chromadb

pacman returning target not found for python-faiss and python-chromadb

What works is a virtual environment:

bash
# Step 1: Create a virtual environment
python -m venv rag_env  

# Step 2: Activate the virtual environment
source rag_env/bin/activate  

# Step 3: Install FAISS and ChromaDB inside the venv
pip install faiss-cpu chromadb  

# Step 4: Verify installation
python -c "import faiss, chromadb; print('FAISS & ChromaDB Ready')"

Once you paste the above commands in terminal it will start collecting FIASS and chromaDB dependencies and start building them :

Terminal creating the rag_env virtual environment while pip collects faiss-cpu and chromadb

Once your all the dependencies will be download it may look like :

pip finishing the faiss-cpu and chromadb install in rag_env, followed by a bash event not found error

The bash: !': event not found line at the bottom of the screenshot comes from the exclamation mark in the verify command as it was first written ('FAISS & ChromaDB Ready!'). Inside double quotes, interactive Bash treats ! as a history expansion (Bash manual), so the command above leaves it out.

Now, everytime you work with RAG automation , you may activate virtual environment with :

bash
source rag_env/bin/activate

for deactivating use :

text
deactivate

Setting up large language models from the CLI

Install the OpenAI Python library

bash
pip install openai

pip install openai completing inside the rag_env virtual environment

Export your API key securely :

bash
export OPENAI_API_KEY="your_api_key_here"

Replace your_api_key_here with your key. The variable lasts until you close the terminal, and the scripts below read it from there.

Terminal activating rag_env and exporting OPENAI_API_KEY

Verify your LLM installation via this command :

bash
python -c "import openai; print('OpenAI API Ready')"
llama-completion --help  # Check that llama.cpp is installed

The first line prints OpenAI API Ready. The second lists llama.cpp’s options; if it says command not found, install or build llama.cpp first.

Running Vector Database Services via Bash

Option 1 : Running FAISS from a bash script

bash
#!/bin/bash
python -c "import faiss; print('FAISS Ready')"

run_faiss.sh check printing FAISS Ready

Save this as run_faiss.sh and execute it :

bash
chmod +x run_faiss.sh
./run_faiss.sh

Option 2 : Running ChromaDB as a Background Service

Start a Chroma server in the background with the chroma command. It keeps its data in the folder you pass to --path (Chroma CLI docs):

bash
chroma run --path ./chroma_data --port 8000 &

It listens on localhost by default. Add --host 0.0.0.0 only if other machines on your network need to reach it.

Option 3 : Creating and Managing Data Pipelines with Bash

A complete RAG workflow includes :

  • Data Collection
  • Embedding Creation
  • Retrieval and Augmentation
  • Text Generation

Bash Script to Automate a Simple RAG Pipeline

bash
#!/bin/bash

# Step 1: Download data
wget -O data.txt "https://example.com/sample-data"

# Step 2: Preprocess text (remove special characters)
sed -i 's/[^a-zA-Z0-9 ]//g' data.txt

# Step 3: Convert text to embeddings using FAISS
python -c "import faiss; print('Generating Embeddings...')"

# Step 4: Store embeddings in ChromaDB
python -c "import chromadb; print('Storing in ChromaDB...')"

# Step 5: Query vector database & retrieve relevant context
python -c "print('Retrieving Relevant Information...')"

# Step 6: Generate response using LLM
llama-completion --model /path/to/model.gguf -no-cnv --prompt "$(cat data.txt)"

echo "RAG Workflow Completed Successfully!"

Simple RAG pipeline run: wget gets a 404 from example.com and llama-cli is not found, yet the script reports success

Treat this script as an outline. Steps 3 to 5 only print messages, and the screenshot, taken with the March 2025 version of the script, shows what happens when it runs as is: wget gets a 404 from the placeholder URL and the model step fails, yet the script still prints its success line. Replace the URL and the model path with your own, and add set -e under the first line if you want the script to stop at the first error. The sections below build the real embedding and search steps.

Now run the following script :

bash
chmod +x rag_pipeline.sh
./rag_pipeline.sh

Automating data preprocessing with Bash

Web Scraping & Data Collection

Web scraping can allow us to fetch any data from online sources. We can use various commands for it…lets look into some of them :

Example 1 : Downloading a webpage with < wget >

bash
wget -O article.html "https://example.com/article"

This saves the webpage as article.html

Example 2 : Extracting Text Content with sed & grep

bash
cat article.html | sed -n '/<p>/,/<\/p>/p' | sed 's/<[^>]*>//g' > content.txt

Here <p> means paragraph, the above command extracts all the paragraphs from the source of web you provided.

Example 3 : Using < curl > and < pup > to extract data from HTML

pup isn’t in Arch’s official repositories; it’s in the AUR. Install it with an AUR helper such as yay:

bash
yay -S pup

Now, extract the article text :

bash
curl -s "https://example.com/article" | pup 'p text{}' > content.txt

Replace https://example.com/article with the article link from which you want to fetch certain data.

Automated Bash Script for Preprocessing

bash
#!/bin/bash

# Step 1: Download the webpage
wget -O article.html "https://example.com/article"

# Step 2: Extract paragraph text
cat article.html | sed -n '/<p>/,/<\/p>/p' | sed 's/<[^>]*>//g' > content.txt

# Step 3: Clean text (remove special characters & extra spaces)
sed -i 's/[^a-zA-Z0-9 ]//g' content.txt
sed -i 's/[[:space:]]\+/ /g' content.txt

# Step 4: Convert to CSV
awk '{print NR "," $0}' content.txt > data.csv

# Step 5: Convert to JSON
awk '{print "{ \"id\": " NR ", \"text\": \"" $0 "\" }"}' content.txt > data.json

echo "Preprocessing Complete: data.csv and data.json are ready!"

Preprocessing script run: wget gets a 404 from example.com, then the script reports data.csv and data.json ready

Now run the script via :

bash
chmod +x preprocess.sh
./preprocess.sh

Automating Document Embedding & Vectorization

After the preprocessing of data, the next step in RAG system is to convert text to embeddings ( numerical vector representations ). We will cover the following things in this section :

  • Running an embedding model with bash
  • Storing and retrieving data in a vector database
  • Managing vector indexing or faster retrievals

For embeddings of data other than text, see this Weights & Biases report on vector embeddings in RAG applications.

Automating Embedding Model Execution

For conversion of text to embedding we need a text conversion model, for this we have two options :

  • OpenAI’s text-embedding-ada-002 ( Cloud Based API )
  • Hugging Face Transformers ( Example – sentence transformers )

OpenAI now lists text-embedding-ada-002 as an older model, and text-embedding-3-small costs $0.02 per million tokens against ada-002’s $0.10 (OpenAI model page, read 18 Nov 2026). The search script below uses sentence-transformers, which runs locally.

Setting Dependencies in Virtual Environment

bash
python -m venv rag_env
source rag_env/bin/activate
pip install sentence-transformers faiss-cpu chromadb openai

Copy and paste the above commands in terminal :

pip downloading torch 2.6.0 for Python 3.13 while installing sentence-transformers

Automating the entire workflow

A master script runs the steps in one go:

bash
#!/bin/bash

echo "Starting RAG Embedding Workflow"

# Step 1: Generate Embeddings
echo "Generating text embeddings..."
./generate_embeddings.sh

# Step 2: Store Embeddings in FAISS
echo "Storing embeddings in FAISS..."
./store_embeddings.sh

# Step 3: Retrieve Sample Query
echo "Testing retrieval..."
./retrieve_vectors.sh

echo "✅ RAG Vector Pipeline Complete!"

Embedding master script run: generate_embeddings.sh, store_embeddings.sh and retrieve_vectors.sh not found

This post doesn’t include generate_embeddings.sh, store_embeddings.sh or retrieve_vectors.sh, and the screenshot shows Bash failing to find them. Write those three scripts before you run this one. The search script in the next section expects the index file vector_index.faiss, which store_embeddings.sh has to create.

you may understand the whole process with each domains by the following table :

STEP TOOL USED COMMANDS
Generate embeddings sentence-transformers ./generate_embeddings.sh
Store embeddings in FAISS FAISS ./store_embeddings.sh
Retrieve similar texts FAISS ./retrieve_vectors.sh
Optimize FAISS index FAISS ( IVF ) ./store_optimized_embeddings.sh
Automate everything Bash Script ./run_rag_pipeline.sh

Automating query processing in RAG

Fetching Queries from Users via CLI

bash
#!/bin/bash

echo "🔍 Enter your query:"
read user_query

# Save the query to a temporary file
echo "$user_query" > query.txt

Automating Search in the Vector Database via CLI

  • Converted into an embedding using the same model used during document embedding
  • Searched in the FAISS vector database to retrieve the closest matches
bash
#!/bin/bash

# Step 1: Activate the virtual environment
source rag_env/bin/activate

# Step 2: Convert the query into an embedding & search in FAISS
python - <<EOF
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer

# Load the query from file
with open("query.txt", "r") as f:
    query = f.read().strip()

# Load the same embedding model
model = SentenceTransformer('all-MiniLM-L6-v2')

# Generate embedding for the query
query_embedding = model.encode([query])

# Load the FAISS index
index = faiss.read_index("vector_index.faiss")

# Search for the top 3 closest embeddings
D, I = index.search(query_embedding, 3)  # Top 3 matches

# Save the retrieved indices
np.savetxt("retrieved_indices.txt", I, fmt="%d")

print(f"Retrieved closest matches: {I}")
EOF

Query embedding and FAISS search script typed into Konsole

Fetching Relevant Context for Generation

  • Extract the original text corresponding to those document indices, we need to…

  • Format the text for use in an LLM

Here is the code snippet :

bash
#!/bin/bash

# Step 1: Activate the virtual environment
source rag_env/bin/activate

# Step 2: Extract relevant text using retrieved indices
python - <<EOF
import json
import numpy as np

# Load the retrieved indices
indices = np.loadtxt("retrieved_indices.txt", dtype=int)

# Load the dataset (text database)
with open("data.json", "r") as f:
    docs = [json.loads(line)['text'] for line in f.readlines()]

# Extract the top matching documents
retrieved_docs = [docs[i] for i in indices if i < len(docs)]

# Save the retrieved contexts to a file
with open("retrieved_context.txt", "w") as f:
    for doc in retrieved_docs:
        f.write(doc + "\n\n")

print("Retrieved context saved in retrieved_context.txt")
EOF

Context extraction script failing with a NumPy traceback because retrieved_indices.txt is missing

In my case there is an error because there are no files created in my directory but in your case, give it a try for sure. Just follow the given steps.

Automating text generation and response handling

Automating model calls for the OpenAI API and Llama

There are two ways to integrate LLM into our pipeline :

  • Locally hosted models ( Llama.cpp, Ollama, or Hugging Face Transformers )
  • Cloud Based API’s ( OpenAI GPT, TogetherAI, Anyscale )

A. Calling the OpenAI API from Bash

For GPT models we can use < curl > to fetch API directly :

NOTE : The below script is for experimental purpose only, you can modify it according to your use and convenience.

bash
#!/bin/bash

# Load the OpenAI API Key (set it in your environment variables)
API_KEY="$OPENAI_API_KEY"

# Read the retrieved context
context=$(cat retrieved_context.txt)

# Define the user query
query=$(cat query.txt)

# Send request to OpenAI API
response=$(curl -s -X POST "https://api.openai.com/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-sol",
    "messages": [
      {"role": "system", "content": "You are an AI assistant that answers questions using provided context."},
      {"role": "user", "content": "Context: '"$context"' \n\n Question: '"$query"'"}
    ]
  }' | jq -r '.choices[0].message.content')

# Save response to a file
echo "$response" > generated_response.txt
echo "Response saved in generated_response.txt"

Save the script as generate_gpt_response.sh. It reads the key you exported earlier, so the key never sits in the file. OpenAI shut down gpt-4 on 23 Oct 2026 and lists gpt-5.6-sol as its replacement (OpenAI deprecations); any model your account can use with Chat Completions works here. The JSON body breaks if the context contains double quotes or line breaks, so build it with jq before you feed it real documents.

Execute the created and saved file with following script :

bash
chmod +x generate_gpt_response.sh
./generate_gpt_response.sh

B. Running a Local Llama Model

Llama.cpp or Ollama are used for offline usage.

Example: Calling Llama.cpp Model :

bash
#!/bin/bash

# Read the retrieved context and query
context=$(cat retrieved_context.txt)
query=$(cat query.txt)

# Call Llama.cpp model with context & query
llama-completion -m models/llama-7B.gguf -no-cnv -p "Context: $context \n\n Question: $query" > generated_response.txt

echo "Response saved in generated_response.txt"

llama-completion is llama.cpp’s one-shot text program, and -no-cnv stops it from opening an interactive chat (llama.cpp completion docs). Point -m at any GGUF model you have downloaded. To keep the model on a separate machine, our private AI server guide covers the hardware.

Save it as generate_llama_response.sh and run it with:

bash
chmod +x generate_llama_response.sh
./generate_llama_response.sh

Post-Processing Responses for Better Output

LLM responses might contain :

  • unwanted extra details
  • repetitive content
  • lack of structured formatting

To clean and format responses, we can use sed, awk, and grep in Bash :

bash
#!/bin/bash

# Read the raw response
response=$(cat generated_response.txt)

# Remove unnecessary blank lines and excessive spacing
cleaned_response=$(echo "$response" | sed '/^\s*$/d' | awk '{$1=$1;print}')

# Save cleaned response
echo "$cleaned_response" > cleaned_response.txt

echo " Cleaned response saved in cleaned_response.txt"

Response cleanup script: cat cannot find generated_response.txt

Formatting and Saving Responses for Further Use

A. Formatting Response into Markdown

You can use the following experimental script :

bash
#!/bin/bash

# Read cleaned response
response=$(cat cleaned_response.txt)

# Add Markdown formatting
echo "## AI Response" > formatted_response.md
echo "" >> formatted_response.md
echo "$response" >> formatted_response.md

echo "Response saved in formatted_response.md"

Markdown formatting script saving formatted_response.md

Run the script for markdown :

bash
chmod +x format_response.sh
./format_response.sh

B. Formatting Response into JSON

Experimental snippet for formatting :

bash
#!/bin/bash

# Read cleaned response
response=$(cat cleaned_response.txt)

# Convert response into JSON format
echo "{\"response\": \"$response\"}" > formatted_response.json

echo "✅ Response saved in formatted_response.json"

For running the script :

bash
chmod +x format_response_json.sh
./format_response_json.sh

Automating the Entire Text Generation Pipeline via CLI

You can use the following format in pipeline for text generation :

bash
#!/bin/bash

echo "Running RAG-based AI Response Generation"

# Step 1: Fetch User Query
echo "Fetching user query..."
./query_pipeline.sh

# Step 2: Generate AI Response
echo "Calling LLM to generate response..."
./generate_gpt_response.sh  # Or use `./generate_llama_response.sh` for local models

# Step 3: Post-process the response
echo "Cleaning and formatting response..."
./post_process_response.sh

# Step 4: Format response for further use
echo "Saving formatted response..."
./format_response.sh

echo "RAG-based AI Response Generation Complete!"

For running the pipeline :

bash
chmod +x generate_full_response.sh
./generate_full_response.sh

Real-world use cases

Automating Research & Knowledge Retrieval

USE CASE :

Academic researchers, teachers. professors, universities and professionals need quick access to relevant information from large text datasets, PDFs and scientific papers.

How RAG + CLI Helps:

  • By automatically searching millions of documents using vector databases.
  • Retrieve highly relevant context without manually browsing papers.
  • Generate concise summaries using AI models like GPT/ Llama

Example CLI Pipeline :

bash
./query_pipeline.sh  # Fetch & process query
./generate_gpt_response.sh  # Generate AI-based summary
cat cleaned_response.txt  # View the final answer

Potential Enhancements :

  • Automate data ingestion from google scholar, ArXiv, or company databases
  • Integrate with speech-to-text for voice-based queries

Automating Customer Support Chatbots

USE CASE :

Companies or call centers often deal with repetitive customer queries, for this a chatbot can automate support tasks :

How RAG + CLI Helps :

  • Uses existing FAQ documents as a knowledge base
  • Provides instant AI-generated responses
  • Can be deployed in Slack, Telegram, or a CLI chatbot

Example Chatbot Script :

bash
#!/bin/bash
while true; do
    echo "💬 Enter your query (or type 'exit' to quit):"
    read user_query
    if [ "$user_query" == "exit" ]; then
        echo "👋 Goodbye!"
        break
    fi
    echo "$user_query" > query.txt
    ./generate_full_response.sh
    cat formatted_response.md
done

Potential Enhancements :

  • Deploy as an API backend for websites
  • Use speech-to-text for voice-based support

Automating Internal Documentation Search for Companies

USE CASE :

Companies need quick search functionality across large internal documents like wikis, PDFs and Confluence.

How RAG + CLI Helps :

  • Employees can search company knowledge bases from the terminal

  • Automatically extracts relevant policies, code snippets, or SOPs

  • Improves developer experience by enabling quick access to logs & troubleshooting docs

Example CLI Search Script :

bash
./query_pipeline.sh  # Fetch query & retrieve docs
./generate_gpt_response.sh  # Generate AI-assisted answer
cat formatted_response.md  # View the response

Potential Enhancements :

  • Index company wiki pages, PDFs, and GitHub repos
  • Deploy as a CLI-based internal assistant

Conclusion

Summary of What We Learnt Till Now :

  • Downloading and cleaning text with wget, sed and awk
  • Turning text into embeddings with sentence-transformers and searching them with FAISS
  • Sending the retrieved context to the OpenAI API, or to a local model through llama.cpp for offline use
  • Cleaning the answers and saving them as Markdown or JSON
  • Example pipelines for research, support chatbots and internal documentation search

Additional Resources and Learning Paths for Referencing :

BONUS :

If you’re new to running LLMs, these guides cover the model side. For a browser chat with a local model instead of scripts, see our CasaOS home brain project.

Self-hosting LLMs in 2026: a guide to privacy, hardware and cost

Vibe coding: what it is, where it came from and its risks

Frequently asked questions

What is Retrieval-Augmented Generation (RAG)?

RAG is a process that enhances Large Language Models (LLMs) by integrating external knowledge during response generation. It retrieves relevant documents from a knowledge base (e.g., FAISS, ChromaDB, or APIs) and uses them as context for generating enriched answers.

Why should I automate RAG workflows?

Automating RAG workflows reduces manual effort, increases speed and scalability, and ensures consistency. Tasks like data preprocessing, embeddings generation, retrieval, API calls, and response formatting are streamlined for efficiency.

What are the prerequisites for setting up a RAG system?

Basics of Bash scripting (loops, variables, exception handling).
Tools like wget, curl, jq, Python, and vector databases (FAISS, ChromaDB).
An understanding of RAG concepts such as retrieval, augmentation, and generation.

What are the advantages of using Bash scripting for automation?

Lightweight and efficient.
Easy integration with other CLI tools.
Supports scheduling and background execution with ease.
Fully customizable and secure.

How can I set up FAISS on my system?

Inside a Python virtual environment, run pip install faiss-cpu. On Arch Linux, pip refuses to install packages system-wide (the externally-managed-environment error), which is why this guide creates rag_env first. For NVIDIA GPUs, the FAISS project's supported route is conda, with faiss-gpu from the pytorch and nvidia channels. The faiss-gpu wheel on PyPI is built for Linux x86-64 only.

Which tools are required to integrate LLMs in the RAG pipeline?

OpenAI GPT or a locally hosted LLM like LLaMA.
Dependencies like sentence-transformers, FAISS, ChromaDB, and APIs like OpenAI.

Can I use RAG offline?

Yes. Once the embedding model has downloaded, sentence-transformers and FAISS run on your own machine, and llama.cpp can write the answer from a local GGUF model. Only the OpenAI API step needs an internet connection.

Written by

Aradhya Chaudhary

Technology enthusiast with a strong experience in open-source contribution. Skilled in Python, DSA (Python, Java and C++), Machine Learning ( NLP ), Deep Learning, Java ( Core ). Pursuing Bachelors of Technology ( B-Tech ) focused on Computer Science from Pranveer Singh Institute of Technology (PSIT).

Comments

No comments yet.

    Read more