UNIX – Terminal – Oh My Zsh Setup

| | | | | | | |

Setup Scripts

For more information on Oh My Zsh, see https://github.com/robbyrussell/oh-my-zsh

Bash
#!/usr/bin/env bash
#
# zsh-setup.sh
#
# Installs and configures Zsh + a cross-platform dynamic MOTD for:
#   - macOS
#   - Ubuntu / Debian
#   - RHEL-family systems: RHEL, Rocky, AlmaLinux, CentOS Stream, Fedora
#
# Run as a normal user with sudo access:
#   bash zsh-setup.sh
#

set -Eeuo pipefail
IFS=$'\n\t'
umask 077

readonly MARKER_BEGIN="# >>> Zsh setup >>>"
readonly MARKER_END="# <<< Zsh setup <<<"

if [[ "${EUID}" -eq 0 ]]; then
    echo "ERROR: Run this script as the normal login user, not as root." >&2
    echo "Example: bash zsh-setup.sh" >&2
    exit 1
fi

if ! command -v sudo >/dev/null 2>&1; then
    echo "ERROR: sudo is required because this script configures system settings and root." >&2
    exit 1
fi

sudo -v

CURRENT_USER="$(id -un)"
USER_HOME="${HOME}"
USER_ZSHRC="${USER_HOME}/.zshrc"
OMZ_DIR="${USER_HOME}/.oh-my-zsh"
STATE_DIR="${USER_HOME}/.local/state/zsh-setup"

WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/zsh-setup.XXXXXX")"
trap 'rm -rf "${WORK_DIR}"' EXIT

mkdir -p "${STATE_DIR}"
chmod 700 "${STATE_DIR}"

fail() {
    echo "ERROR: $*" >&2
    exit 1
}

state_file() {
    printf '%s/%s' "${STATE_DIR}" "$1"
}

state_put_if_absent() {
    local name="$1"
    local value="$2"
    local file

    file="$(state_file "${name}")"
    if [[ ! -f "${file}" ]]; then
        printf '%s\n' "${value}" > "${file}"
        chmod 600 "${file}"
    fi
}

detect_platform() {
    case "$(uname -s)" in
        Darwin)
            OS_FAMILY="macos"
            ;;
        Linux)
            [[ -r /etc/os-release ]] || fail "Cannot identify this Linux distribution: /etc/os-release is missing."
            # shellcheck disable=SC1091
            . /etc/os-release

            case " ${ID:-} ${ID_LIKE:-} " in
                *" debian "*|*" ubuntu "*)
                    OS_FAMILY="debian"
                    ;;
                *" rhel "*|*" fedora "*|*" centos "*|*" rocky "*|*" almalinux "*)
                    OS_FAMILY="redhat"
                    ;;
                *)
                    fail "Unsupported Linux distribution. Supported: Ubuntu/Debian and RHEL-family distributions."
                    ;;
            esac
            ;;
        *)
            fail "Unsupported operating system: $(uname -s)"
            ;;
    esac
}

get_account_shell() {
    local account="$1"
    local shell_path=""

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        shell_path="$(dscl . -read "/Users/${account}" UserShell 2>/dev/null | awk 'NR == 1 { print $2 }')"
    else
        shell_path="$(getent passwd "${account}" | awk -F: 'NR == 1 { print $7 }')"
    fi

    [[ -n "${shell_path}" ]] || fail "Unable to determine the current login shell for ${account}."
    printf '%s\n' "${shell_path}"
}

get_root_home() {
    local root_home=""

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        root_home="$(dscl . -read /Users/root NFSHomeDirectory 2>/dev/null | awk 'NR == 1 { print $2 }')"
    else
        root_home="$(getent passwd root | awk -F: 'NR == 1 { print $6 }')"
    fi

    [[ -n "${root_home}" ]] || fail "Unable to determine root's home directory."
    printf '%s\n' "${root_home}"
}

strip_managed_block() {
    local input_file="$1"
    local output_file="$2"

    if [[ ! -e "${input_file}" && ! -L "${input_file}" ]]; then
        : > "${output_file}"
        return 0
    fi

    awk \
        -v begin="${MARKER_BEGIN}" \
        -v end="${MARKER_END}" '
        $0 == begin {
            if (inside) invalid = 1
            inside = 1
            next
        }
        $0 == end {
            if (!inside) {
                invalid = 1
            } else {
                inside = 0
            }
            next
        }
        !inside { print }
        END {
            if (inside || invalid) exit 2
        }
    ' "${input_file}" > "${output_file}" \
        || fail "Malformed managed Zsh block detected in ${input_file}; no changes were made."
}

set_login_shell() {
    local account="$1"
    local shell_path="$2"

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        sudo chsh -s "${shell_path}" "${account}"
    elif command -v usermod >/dev/null 2>&1; then
        sudo usermod -s "${shell_path}" "${account}"
    else
        sudo chsh -s "${shell_path}" "${account}"
    fi
}

install_prerequisites() {
    local zsh_previously_available="false"
    command -v zsh >/dev/null 2>&1 && zsh_previously_available="true"

    case "${OS_FAMILY}" in
        macos)
            command -v zsh >/dev/null 2>&1 || fail "Zsh was not found. macOS normally includes /bin/zsh."
            if ! command -v git >/dev/null 2>&1; then
                echo "Git is required to install Oh My Zsh."
                echo "Install the macOS Command Line Tools, then rerun:"
                echo "  xcode-select --install"
                exit 1
            fi
            # Silence default macOS "Last login:" banner for the user
            touch "${USER_HOME}/.hushlogin"
            # Allow Wi-Fi SSID visibility where supported
            if sudo ipconfig sethidewifiinfo 0 >/dev/null 2>&1; then
                echo "Updated macOS Wi-Fi SSID visibility setting."
            fi
            ;;
        debian)
            sudo apt-get update
            sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y zsh git
            ;;
        redhat)
            if command -v dnf >/dev/null 2>&1; then
                sudo dnf install -y zsh git
            elif command -v yum >/dev/null 2>&1; then
                sudo yum install -y zsh git
            else
                fail "Neither dnf nor yum is available on this RHEL-family system."
            fi
            ;;
    esac

    state_put_if_absent "zsh-installed-by-script" \
        "$([[ "${zsh_previously_available}" == "true" ]] && printf 'false' || printf 'true')"
}

install_oh_my_zsh() {
    if [[ -e "${OMZ_DIR}" && ! -d "${OMZ_DIR}" ]]; then
        fail "${OMZ_DIR} exists but is not a directory."
    fi

    if [[ ! -d "${OMZ_DIR}" ]]; then
        echo "Installing Oh My Zsh for ${CURRENT_USER}..."
        git clone --depth=1 https://github.com/ohmyzsh/ohmyzsh.git "${OMZ_DIR}"
        printf 'true\n' > "$(state_file "omz-installed-by-script")"
        chmod 600 "$(state_file "omz-installed-by-script")"
    else
        echo "Oh My Zsh already exists at ${OMZ_DIR}; leaving it unchanged."
        state_put_if_absent "omz-installed-by-script" "false"
    fi
}

# Cross-platform MOTD helper function embedded into Zsh config
build_motd_function() {
    cat <<'EOF'
__zsh_custom_motd() {
  # Only print on interactive shells
  [[ -o interactive ]] || return 0

  local os_name="" hostname_val="" serial_val="" iface="" wifi_name=""
  local ip_addr="" subnet_mask="" router_ip="" cidr_suffix="" ip_cidr=""
  local dns_server="" mac_addr=""

  hostname_val="$(hostname -s 2>/dev/null || hostname 2>/dev/null || printf 'unknown')"

  case "$(uname -s)" in
    Darwin)
      local ver build
      ver="$(sw_vers -productVersion 2>/dev/null || true)"
      build="$(sw_vers -buildVersion 2>/dev/null || true)"
      os_name="macOS ${ver}${build:+ (${build})}"
      serial_val="$(ioreg -rd1 -c IOPlatformExpertDevice 2>/dev/null | awk -F'"' '/IOPlatformSerialNumber/ {print $4; exit}')"
      [[ -z "$serial_val" ]] && serial_val="$(system_profiler SPHardwareDataType 2>/dev/null | awk -F': ' '/Serial Number/ {print $2; exit}')"
      [[ -z "$serial_val" ]] && serial_val="N/A"

      iface="en0"
      wifi_name="$(ipconfig getsummary "$iface" 2>/dev/null | awk -F' : ' '/ SSID :/ {print $2; exit}')"
      [[ -z "$wifi_name" ]] && wifi_name="Not Connected / N/A"

      ip_addr="$(ipconfig getifaddr "$iface" 2>/dev/null || true)"
      subnet_mask="$(ipconfig getoption "$iface" subnet_mask 2>/dev/null || true)"
      router_ip="$(ipconfig getoption "$iface" router 2>/dev/null || true)"
      mac_addr="$(ifconfig "$iface" 2>/dev/null | awk '/ether / {print $2; exit}')"
      dns_server="$(networksetup -getdnsservers Wi-Fi 2>/dev/null | head -n 1 || true)"
      if [[ -z "$dns_server" || "$dns_server" == *"There aren't any"* ]]; then
        dns_server="$(awk '/^nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null || printf 'DHCP / Default')"
      fi
      ;;

    Linux)
      if [[ -r /etc/os-release ]]; then
        os_name="$(awk -F= '/^PRETTY_NAME=/ {gsub(/^"|"/, "", $2); print $2; exit}' /etc/os-release)"
      fi
      [[ -z "$os_name" ]] && os_name="Linux ($(uname -r))"

      for sfile in /sys/class/dmi/id/product_serial /sys/devices/virtual/dmi/id/product_serial; do
        if [[ -r "$sfile" ]]; then
          serial_val="$(tr -d '[:space:]' < "$sfile" 2>/dev/null || true)"
          [[ -n "$serial_val" ]] && break
        fi
      done
      [[ -z "$serial_val" ]] && serial_val="N/A"

      # Detect primary non-loopback interface
      iface="$(ip -o route show default 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="dev") {print $(i+1); exit}}')"
      if [[ -z "$iface" ]]; then
        iface="$(ip -o link show up 2>/dev/null | awk -F': ' '$2 != "lo" {print $2; exit}')"
      fi
      [[ -z "$iface" ]] && iface="none"

      if [[ "$iface" != "none" ]]; then
        ip_addr="$(ip -4 -o addr show dev "$iface" 2>/dev/null | awk '{print $4}' | head -n 1 | cut -d/ -f1)"
        cidr_suffix="$(ip -4 -o addr show dev "$iface" 2>/dev/null | awk '{print $4}' | head -n 1 | cut -d/ -f2)"
        router_ip="$(ip -4 route show default dev "$iface" 2>/dev/null | awk '/default via/ {print $3; exit}')"
        mac_addr="$(cat "/sys/class/net/${iface}/address" 2>/dev/null || ip -o link show dev "$iface" 2>/dev/null | awk '/link\/ether/ {print $2; exit}')"

        if [[ -n "$cidr_suffix" ]]; then
          local mask_int i bits octet
          mask_int=$(( cidr_suffix == 0 ? 0 : (0xffffffff << (32 - cidr_suffix)) & 0xffffffff ))
          subnet_mask="$(( (mask_int >> 24) & 255 )).$(( (mask_int >> 16) & 255 )).$(( (mask_int >> 8) & 255 )).$(( mask_int & 255 ))"
        fi

        if command -v nmcli >/dev/null 2>&1; then
          wifi_name="$(nmcli -t -f active,ssid dev wifi 2>/dev/null | awk -F: '$1=="yes" {print $2; exit}')"
        elif [[ -r "/proc/net/wireless" ]] && awk -v dev="$iface" '$1 ~ ("^"dev":") {found=1} END {exit !found}' /proc/net/wireless; then
          wifi_name="$(iw dev "$iface" link 2>/dev/null | awk -F': ' '/SSID:/ {print $2; exit}')"
        fi
        [[ -z "$wifi_name" ]] && wifi_name="N/A (Wired / Unreported)"
      else
        wifi_name="N/A"
      fi

      dns_server="$(awk '/^nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null || printf 'N/A')"
      ;;
  esac

  if [[ -n "$ip_addr" && -n "$cidr_suffix" ]]; then
    ip_cidr="${ip_addr}/${cidr_suffix}"
  elif [[ -n "$ip_addr" && -n "$subnet_mask" ]]; then
    local o1 o2 o3 o4 count=0 octet
    IFS=. read -r o1 o2 o3 o4 <<< "$subnet_mask"
    for octet in "$o1" "$o2" "$o3" "$o4"; do
      case "$octet" in
        255) count=$((count + 8)) ;;
        254) count=$((count + 7)) ;;
        252) count=$((count + 6)) ;;
        248) count=$((count + 5)) ;;
        240) count=$((count + 4)) ;;
        224) count=$((count + 3)) ;;
        192) count=$((count + 2)) ;;
        128) count=$((count + 1)) ;;
        0)   ;;
      esac
    done
    ip_cidr="${ip_addr}/${count}"
  else
    ip_addr="${ip_addr:-Not Connected}"
    ip_cidr="${ip_addr}"
  fi

  [[ -z "$subnet_mask" ]] && subnet_mask="N/A"
  [[ -z "$router_ip" ]] && router_ip="N/A"
  [[ -z "$mac_addr" ]] && mac_addr="N/A"
  [[ -z "$dns_server" ]] && dns_server="N/A"

  printf 'System Information\n'
  printf '  OS           : %s\n' "$os_name"
  printf '  Hostname     : %s\n' "$hostname_val"
  printf '  Serial Number: %s\n' "$serial_val"
  printf '\nNetwork Information (%s)\n' "$iface"
  printf '  Wi-Fi SSID   : %s\n' "$wifi_name"
  printf '  IP Address   : %s\n' "$ip_addr"
  printf '  Subnet Mask  : %s\n' "$subnet_mask"
  printf '  Router       : %s\n' "$router_ip"
  printf '  IP CIDR      : %s\n' "$ip_cidr"
  printf '  DNS Server   : %s\n' "$dns_server"
  printf '  MAC Address  : %s\n\n' "$mac_addr"
}
__zsh_custom_motd
EOF
}

configure_user_zshrc() {
    local stripped_file="${WORK_DIR}/user.zshrc.stripped"
    local result_file="${WORK_DIR}/user.zshrc.result"
    local motd_code=""
    local omz_snippet=""

    strip_managed_block "${USER_ZSHRC}" "${stripped_file}"
    motd_code="$(build_motd_function)"

    if ! grep -Fq "oh-my-zsh.sh" "${stripped_file}"; then
        omz_snippet=$(cat <<'EOF'
export ZSH="${HOME}/.oh-my-zsh"

if [[ -r "${ZSH}/oh-my-zsh.sh" ]]; then
    ZSH_THEME=""
    source "${ZSH}/oh-my-zsh.sh"
fi
EOF
)
    fi

    {
        cat "${stripped_file}"
        [[ -s "${stripped_file}" ]] && printf '\n'

        printf '%s\n' "${MARKER_BEGIN}"
        if [[ -n "${omz_snippet}" ]]; then
            printf '%s\n\n' "${omz_snippet}"
        fi
        cat <<'EOF'
# Custom prompt: timestamp, complete working directory, and privilege status.
PROMPT='%F{cyan}[%D{%Y-%m-%d %H:%M:%S}]%f %F{blue}%d%f %(#.%F{red}[root]%f.%F{green}[user]%f) %# '
RPROMPT=''
EOF
        printf '\n%s\n' "${motd_code}"
        printf '%s\n' "${MARKER_END}"
    } > "${result_file}"

    cat "${result_file}" > "${USER_ZSHRC}"
    echo "Configured ${USER_ZSHRC}."
}

configure_root_zshrc() {
    local root_zshrc="$1"
    local source_file="${WORK_DIR}/root.zshrc.source"
    local stripped_file="${WORK_DIR}/root.zshrc.stripped"
    local result_file="${WORK_DIR}/root.zshrc.result"

    if sudo test -e "${root_zshrc}"; then
        sudo cat "${root_zshrc}" > "${source_file}"
    else
        : > "${source_file}"
    fi

    strip_managed_block "${source_file}" "${stripped_file}"

    {
        cat "${stripped_file}"
        [[ -s "${stripped_file}" ]] && printf '\n'

        cat <<EOF
${MARKER_BEGIN}
# Custom prompt: timestamp, complete working directory, and privilege status.
PROMPT='%F{cyan}[%D{%Y-%m-%d %H:%M:%S}]%f %F{blue}%d%f %(#.%F{red}[root]%f.%F{green}[user]%f) %# '
RPROMPT=''
${MARKER_END}
EOF
    } > "${result_file}"

    if ! sudo test -e "${root_zshrc}"; then
        sudo touch "${root_zshrc}"
        sudo chmod 600 "${root_zshrc}"
    fi

    sudo sh -c 'cat "$1" > "$2"' sh "${result_file}" "${root_zshrc}"
    echo "Configured ${root_zshrc}."
}

detect_platform
install_prerequisites

ZSH_BIN="$(command -v zsh)"
[[ "${ZSH_BIN}" == /* ]] || fail "Unable to determine an absolute path for zsh."

if [[ -r /etc/shells ]] && ! grep -Fqx "${ZSH_BIN}" /etc/shells; then
    fail "${ZSH_BIN} is not listed in /etc/shells."
fi

ROOT_HOME="$(get_root_home)"
ROOT_ZSHRC="${ROOT_HOME}/.zshrc"

state_put_if_absent "user-original-shell" "$(get_account_shell "${CURRENT_USER}")"
state_put_if_absent "root-original-shell" "$(get_account_shell root)"
state_put_if_absent "zsh-path" "${ZSH_BIN}"

install_oh_my_zsh
configure_user_zshrc
configure_root_zshrc "${ROOT_ZSHRC}"

echo "Setting persistent login shells to Zsh..."
set_login_shell "${CURRENT_USER}" "${ZSH_BIN}"
set_login_shell root "${ZSH_BIN}"

cat <<EOF

Setup complete.

Configured:
  User account: ${CURRENT_USER}
  User shell:   ${ZSH_BIN}
  Root shell:   ${ZSH_BIN}
  User config:  ${USER_ZSHRC}
  Root config:  ${ROOT_ZSHRC}

EOF

if [[ -t 0 && -t 1 ]]; then
    exec "${ZSH_BIN}" -l
fi

Removal Assistance

As much as I like Oh My Zsh sometimes you have to go back to original terminal as not all things are supported.

Bash
#!/usr/bin/env bash
#
# zsh-uninstall.sh
#
# Removes only the managed Zsh configuration created by setup-zsh.sh.
#
# Actions:
#   - Removes the managed prompt from the user and root .zshrc files.
#   - Restores the previously recorded login shells for the user and root.
#   - Removes Oh My Zsh only if this setup cloned it.
#   - Optionally removes the Zsh package on Linux if this setup installed it.
#
# Usage:
#   bash zsh-uninstall.sh
#   bash zsh-uninstall.sh --purge-zsh
#

set -Eeuo pipefail
IFS=$'\n\t'
umask 077

readonly MARKER_BEGIN="# >>> Zsh setup >>>"
readonly MARKER_END="# <<< Zsh setup <<<"

if [[ "${EUID}" -eq 0 ]]; then
    echo "ERROR: Run this script as the normal login user, not as root."
    echo "Example: bash zsh-uninstall.sh [--purge-zsh]"
    exit 1
fi

PURGE_ZSH="false"

case "${1:-}" in
    "")
        ;;
    --purge-zsh)
        PURGE_ZSH="true"
        ;;
    *)
        echo "Usage: $0 [--purge-zsh]"
        exit 1
        ;;
esac

if ! command -v sudo >/dev/null 2>&1; then
    echo "ERROR: sudo is required because this script restores root's shell and configuration."
    exit 1
fi

sudo -v

CURRENT_USER="$(id -un)"
USER_HOME="${HOME}"
USER_ZSHRC="${USER_HOME}/.zshrc"
OMZ_DIR="${USER_HOME}/.oh-my-zsh"
STATE_DIR="${USER_HOME}/.local/state/zsh-setup"

TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="${USER_HOME}/zsh-uninstall-backup-${TIMESTAMP}"

WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/zsh-uninstall.XXXXXX")"
trap 'rm -rf "${WORK_DIR}"' EXIT

mkdir -p "${BACKUP_DIR}"
chmod 700 "${BACKUP_DIR}"

fail() {
    echo "ERROR: $*" >&2
    exit 1
}

detect_platform() {
    case "$(uname -s)" in
        Darwin)
            OS_FAMILY="macos"
            ;;
        Linux)
            [[ -r /etc/os-release ]] || fail "Cannot identify this Linux distribution: /etc/os-release is missing."
            # shellcheck disable=SC1091
            . /etc/os-release

            case " ${ID:-} ${ID_LIKE:-} " in
                *" debian "*|*" ubuntu "*)
                    OS_FAMILY="debian"
                    ;;
                *" rhel "*|*" fedora "*|*" centos "*|*" rocky "*|*" almalinux "*)
                    OS_FAMILY="redhat"
                    ;;
                *)
                    fail "Unsupported Linux distribution."
                    ;;
            esac
            ;;
        *)
            fail "Unsupported operating system: $(uname -s)"
            ;;
    esac
}

state_read() {
    local name="$1"
    local file="${STATE_DIR}/${name}"
    local value=""

    if [[ -f "${file}" ]]; then
        IFS= read -r value < "${file}" || true
    fi

    printf '%s\n' "${value}"
}

get_root_home() {
    local root_home=""

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        root_home="$(
            dscl . -read /Users/root NFSHomeDirectory 2>/dev/null \
                | awk 'NR == 1 { print $2 }'
        )"
    else
        root_home="$(
            getent passwd root \
                | awk -F: 'NR == 1 { print $6 }'
        )"
    fi

    [[ -n "${root_home}" ]] || fail "Unable to determine root's home directory."

    printf '%s\n' "${root_home}"
}

strip_managed_block() {
    local input_file="$1"
    local output_file="$2"

    if [[ ! -e "${input_file}" && ! -L "${input_file}" ]]; then
        : > "${output_file}"
        return 0
    fi

    awk \
        -v begin="${MARKER_BEGIN}" \
        -v end="${MARKER_END}" '
        $0 == begin {
            if (inside) {
                invalid = 1
            }
            inside = 1
            next
        }

        $0 == end {
            if (!inside) {
                invalid = 1
            } else {
                inside = 0
            }
            next
        }

        !inside {
            print
        }

        END {
            if (inside || invalid) {
                exit 2
            }
        }
    ' "${input_file}" > "${output_file}" \
        || fail "Malformed managed Zsh block detected in ${input_file}; no changes were made."
}

is_safe_login_shell() {
    local shell_path="$1"

    [[ "${shell_path}" == /* ]] || return 1
    [[ "${shell_path}" != *$'\n'* ]] || return 1
    [[ -x "${shell_path}" ]] || return 1

    if [[ -r /etc/shells ]] && grep -Fqx "${shell_path}" /etc/shells; then
        return 0
    fi

    case "${shell_path}" in
        /usr/sbin/nologin|/sbin/nologin)
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

set_login_shell() {
    local account="$1"
    local shell_path="$2"

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        sudo chsh -s "${shell_path}" "${account}"
    elif command -v usermod >/dev/null 2>&1; then
        sudo usermod -s "${shell_path}" "${account}"
    else
        sudo chsh -s "${shell_path}" "${account}"
    fi
}

backup_user_file() {
    if [[ -e "${USER_ZSHRC}" || -L "${USER_ZSHRC}" ]]; then
        cat "${USER_ZSHRC}" > "${BACKUP_DIR}/user.zshrc.before-uninstall"
        chmod 600 "${BACKUP_DIR}/user.zshrc.before-uninstall"
        echo "Backed up ${USER_ZSHRC}."
    fi
}

backup_root_file() {
    local root_zshrc="$1"

    if sudo test -e "${root_zshrc}"; then
        sudo cat "${root_zshrc}" > "${BACKUP_DIR}/root.zshrc.before-uninstall"
        chmod 600 "${BACKUP_DIR}/root.zshrc.before-uninstall"
        echo "Backed up ${root_zshrc}."
    fi
}

remove_user_managed_block() {
    local stripped_file="${WORK_DIR}/user.zshrc.stripped"

    if [[ ! -e "${USER_ZSHRC}" && ! -L "${USER_ZSHRC}" ]]; then
        echo "No user .zshrc found; nothing to remove."
        return 0
    fi

    strip_managed_block "${USER_ZSHRC}" "${stripped_file}"
    cat "${stripped_file}" > "${USER_ZSHRC}"
    echo "Removed managed content from ${USER_ZSHRC}."
}

remove_root_managed_block() {
    local root_zshrc="$1"
    local source_file="${WORK_DIR}/root.zshrc.source"
    local stripped_file="${WORK_DIR}/root.zshrc.stripped"

    if ! sudo test -e "${root_zshrc}"; then
        echo "No root .zshrc found; nothing to remove."
        return 0
    fi

    sudo cat "${root_zshrc}" > "${source_file}"
    strip_managed_block "${source_file}" "${stripped_file}"

    sudo sh -c 'cat "$1" > "$2"' sh "${stripped_file}" "${root_zshrc}"
    echo "Removed managed content from ${root_zshrc}."
}

restore_shell_if_recorded() {
    local account="$1"
    local state_name="$2"
    local original_shell

    original_shell="$(state_read "${state_name}")"

    if [[ -z "${original_shell}" ]]; then
        echo "No recorded original shell exists for ${account}; leaving its current shell unchanged."
        return 0
    fi

    if ! is_safe_login_shell "${original_shell}"; then
        echo "Recorded shell for ${account} is unavailable or unsafe: ${original_shell}"
        echo "Leaving ${account}'s current shell unchanged."
        return 0
    fi

    set_login_shell "${account}" "${original_shell}"
    echo "Restored ${account}'s login shell to ${original_shell}."
}

remove_oh_my_zsh_if_owned() {
    local owned_by_script

    owned_by_script="$(state_read "omz-installed-by-script")"

    if [[ "${owned_by_script}" != "true" ]]; then
        echo "Oh My Zsh was not installed by this setup script; leaving ${OMZ_DIR} unchanged."
        return 0
    fi

    if [[ -d "${OMZ_DIR}" ]]; then
        echo "Backing up Oh My Zsh to ${BACKUP_DIR}/oh-my-zsh..."
        cp -Rp "${OMZ_DIR}" "${BACKUP_DIR}/oh-my-zsh"
        rm -rf "${OMZ_DIR}"
        echo "Removed ${OMZ_DIR}."
    else
        echo "Oh My Zsh directory was already absent."
    fi
}

accounts_still_using_zsh() {
    if [[ "${OS_FAMILY}" == "macos" ]]; then
        return 0
    fi

    getent passwd \
        | awk -F: '$7 ~ /\/zsh$/ { print $1 }'
}

purge_zsh_if_requested() {
    local installed_by_script
    local zsh_users

    if [[ "${PURGE_ZSH}" != "true" ]]; then
        echo "Zsh remains installed."
        return 0
    fi

    installed_by_script="$(state_read "zsh-installed-by-script")"

    if [[ "${installed_by_script}" != "true" ]]; then
        echo "Zsh was not installed by this setup script; leaving it installed."
        return 0
    fi

    if [[ "${OS_FAMILY}" == "macos" ]]; then
        echo "macOS provides Zsh as part of the operating system; it will not be removed."
        return 0
    fi

    zsh_users="$(accounts_still_using_zsh || true)"

    if [[ -n "${zsh_users}" ]]; then
        echo "Zsh was not removed because these accounts still use a Zsh login shell:"
        printf '  %s\n' ${zsh_users}
        return 0
    fi

    case "${OS_FAMILY}" in
        debian)
            sudo apt-get purge -y zsh
            ;;
        redhat)
            if command -v dnf >/dev/null 2>&1; then
                sudo dnf remove -y zsh
            elif command -v yum >/dev/null 2>&1; then
                sudo yum remove -y zsh
            else
                fail "Neither dnf nor yum is available."
            fi
            ;;
    esac

    echo "Zsh package removed."
}

detect_platform

ROOT_HOME="$(get_root_home)"
ROOT_ZSHRC="${ROOT_HOME}/.zshrc"

backup_user_file
backup_root_file "${ROOT_ZSHRC}"

remove_user_managed_block
remove_root_managed_block "${ROOT_ZSHRC}"

restore_shell_if_recorded "${CURRENT_USER}" "user-original-shell"
restore_shell_if_recorded root "root-original-shell"

remove_oh_my_zsh_if_owned
purge_zsh_if_requested

rm -rf "${STATE_DIR}"

cat <<EOF

Uninstall complete.

Backup directory:
  ${BACKUP_DIR}

Close and reopen the terminal, or log out and back in, for the restored login
shell to take effect.
EOF
Originally Posted on January 17, 2017
Last Updated on November 25, 2026

All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.