Josi's LAB
June 17, 2025

Switch PDBs : An Interactive Oracle SQL*Plus Script

Switch PDBs : An Interactive Oracle SQL*Plus Script

Welcome to Hexacats Labs, where we don’t just write scripts...we purrfect them.

If you’ve ever logged into your Oracle container database (CDB) and thought, "Which PDB am I in again?" or "Wait, why am I always in CDB$ROOT?", then this is the script you didn’t know you needed but now you won’t want to live without it.

What Is It?

This is a Bash script that lets you interactively choose a PDB (Pluggable Database) and jumps you straight into SQL*Plus, already switched to the right container. No more typing:

alter session set container=FREEPDB42;

Here is the code:


vi connect_pdb.sh
# Paste the following inside vi

#!/bin/bash

export ORACLE_HOME=/opt/oracle/product/23ai/dbhomeFree
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=FREE

PDBS=("FREEPDB1" "FREEPDB2" "FREEPDB3" "FREEPDB4" "FREEPDB5")

list_pdbs() {
    echo "Available Oracle PDBs:"
    for i in "${!PDBS[@]}"; do
        echo "$((i+1)). ${PDBS[$i]}"
    done
}

echo "Connect to an Oracle PDB (interactive session)"
echo "----------------------------------------------"
list_pdbs
echo "0. Exit"

read -p "Select the PDB number: " choice

if [[ $choice -eq 0 ]]; then
    echo "Exiting..."
    exit 0
elif [[ $choice -gt 0 && $choice -le ${#PDBS[@]} ]]; then
    selected_pdb="${PDBS[$((choice-1))]}"
    echo "Connecting to PDB $selected_pdb..."

    TMP_SCRIPT=$(mktemp)
    {
        echo "alter session set container=$selected_pdb;"
        echo "show con_name;"
        echo "prompt Connected to PDB $selected_pdb."
    } > "$TMP_SCRIPT"

    sqlplus / as sysdba @"$TMP_SCRIPT"
    rm -f "$TMP_SCRIPT"
else
    echo "Invalid option!"
    exit 1
fi

# Save and exit vi, then run:

chmod +x connect_pdb.sh
./connect_pdb.sh
  


That’s it, simple, useful, and no more jumping through CDB$ROOT hoops just to get to your PDB.

See you in the next post , maybe something with less bash and more chaos.

Clotilde, from Hexacats Labs!