clean 安全清理磁盘
先用 --dry-run 查看磁盘占用和将执行的步骤,确认后再加 -y 真正清理。默认不做 docker prune,也不删内核。
$ curl -fsSL xyz.sh/clean | bash
一览
- 做什么
- 先用 --dry-run 查看磁盘占用和将执行的步骤,确认后再加 -y 真正清理。默认不做 docker prune,也不删内核。
- 支持的系统
- Debian, Ubuntu, CentOS, Rocky, AlmaLinux · 需要 root
- 命令
curl -fsSL xyz.sh/clean | bash- 会改动什么
- 偏安全的一次性清理:apt / yum / dnf 缓存、journal 真空到 100M、已禁用的旧 snap 修订、/tmp 中超过 7 天且未被占用的文件,以及 /var/log 里过大的已轮转日志。会打印清理前后的 df。docker system prune 需加 --docker(不加 -a / --volumes)。旧内核需加 --kernels,且永远跳过正在运行的内核。--dry-run 只列出计划;不加 -y 会先确认。
- 如何还原
- 这是一次性清理,不安装常驻服务,也没有需要卸载的组件。
- 上次核实
cleanupb261c9d88934e7bb710b30b3e66ca76b0bbf950880b50eacac68b678cc68cceb
· 与 curl 拿到的脚本一致,也可访问 /clean.sh.sha256
所有脚本都通过 bash -n 与 ShellCheck 检查,并在 Debian 12/11、Ubuntu 24.04/22.04/20.04/18.04、Rocky 9、AlmaLinux 9、CentOS 7 的官方 Docker 镜像中以 root 运行 curl | bash 测试(结果见各页“容器测试结果”)。容器里没有 systemd、内核模块和真实公网线路,相关部分需要在真实 VPS 上确认。
它会做什么
偏安全的一次性清理:apt / yum / dnf 缓存、journal 真空到 100M、已禁用的旧 snap 修订、/tmp 中超过 7 天且未被占用的文件,以及 /var/log 里过大的已轮转日志。会打印清理前后的 df。docker system prune 需加 --docker(不加 -a / --volumes)。旧内核需加 --kernels,且永远跳过正在运行的内核。--dry-run 只列出计划;不加 -y 会先确认。
容器测试结果
在各发行版官方 Docker 镜像中以 root、无终端方式运行 curl | bash 的结果。partial 表示容器内无法完整验证(例如没有 systemd、内核模块或测速协议被测试环境的代理拦截),需要在真实 VPS 上确认。 (2026-11-12)
| OS | 结果 |
|---|---|
| debian:12 | pass |
| debian:11 | pass |
| ubuntu:24.04 | pass |
| ubuntu:22.04 | pass |
| ubuntu:20.04 | pass |
| ubuntu:18.04 | pass |
| rockylinux:9 | pass |
| almalinux:9 | pass |
| centos:7 | pass |
常见问题
- 会不会删掉正在用的文件或内核?
- 默认只清理软件源缓存、journal(真空到 100M)、已禁用的旧 snap 修订、/tmp 中超过 7 天且未被占用的文件,以及 /var/log 里过大的已轮转日志。不会去 truncate 正在写的日志。旧内核只有加 --kernels 才会处理,并且会跳过 uname -r 正在运行的那个。
- 需要 root 吗?
- 需要。清理的目录属于系统缓存和日志。
- --docker 会删除我的容器数据吗?
- 不会加 -a,也不会带 --volumes,只相当于 docker system prune -f,去掉未使用的镜像、已停止的容器和未使用的网络。正在用的容器和具名卷会保留。仍建议先 --dry-run,并在生产机器上再确认一遍。
- 支持哪些系统?
- 声明支持 Debian、Ubuntu、CentOS、Rocky、AlmaLinux。软件源清理会按 apt / dnf / yum 自动选择。
入门指南
完整源码
以下就是 curl 实际拿到的内容(公共库 + 脚本正文)。运行前请先读一遍。
#!/usr/bin/env bash
# Served by xyz.sh/clean
# Human-readable page: https://xyz.sh/clean
# This file is the common library followed by the script body.
# No telemetry is added by xyz.sh.
# =============================================================================
# xyz.sh common library
# Shared helpers for every script served by xyz.sh.
#
# Promises:
# - No telemetry, analytics, or background "phone-home" calls
# - No hidden installs or config changes beyond what the script announces
# - Official upstream URLs are printed before any remote code is executed
# - Destructive or system-changing steps ask for confirmation (or YES=1 / -y)
# =============================================================================
if [[ -n "${XYZ_COMMON_LOADED:-}" ]]; then
# When sourced a second time, return. When executed as a file, return fails.
# shellcheck disable=SC2317
return 0 2>/dev/null || true
fi
# shellcheck disable=SC2034
XYZ_COMMON_LOADED=1
set -euo pipefail
XYZ_VERSION="1.5.0"
XYZ_BASE="${XYZ_BASE:-https://xyz.sh}"
XYZ_NAME="${XYZ_NAME:-unknown}"
# --- language ---------------------------------------------------------------
# Override with XYZ_LANG=zh or XYZ_LANG=en.
if [[ -z "${XYZ_LANG:-}" ]]; then
case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
zh*|ZH*|cmn*|CMN*) XYZ_LANG="zh" ;;
*) XYZ_LANG="en" ;;
esac
fi
xyz_t() {
# xyz_t "English text" "中文文本"
if [[ "${XYZ_LANG}" == "zh" ]]; then
printf '%s' "${2:-$1}"
else
printf '%s' "$1"
fi
}
# --- colors (TTY only) ------------------------------------------------------
# XYZ_COLOR=always|never|auto (default auto: TTY and no NO_COLOR); --no-color.
_xyz_color=0
case "${XYZ_COLOR:-auto}" in
always) _xyz_color=1 ;;
never) _xyz_color=0 ;;
*) [[ -t 1 && -z "${NO_COLOR:-}" ]] && _xyz_color=1 ;;
esac
[[ "${XYZ_NO_COLOR:-0}" == "1" ]] && _xyz_color=0
if [[ "${_xyz_color}" == "1" ]]; then
XYZ_C_RESET=$'\033[0m'
XYZ_C_BOLD=$'\033[1m'
XYZ_C_DIM=$'\033[2m'
XYZ_C_RED=$'\033[31m'
XYZ_C_GREEN=$'\033[32m'
XYZ_C_YELLOW=$'\033[33m'
XYZ_C_CYAN=$'\033[36m'
else
XYZ_C_RESET=""
XYZ_C_BOLD=""
XYZ_C_DIM=""
XYZ_C_RED=""
XYZ_C_GREEN=""
XYZ_C_YELLOW=""
XYZ_C_CYAN=""
fi
xyz_info() { printf '%s[INFO]%s %s\n' "${XYZ_C_GREEN}" "${XYZ_C_RESET}" "$*"; }
xyz_warn() { printf '%s[WARN]%s %s\n' "${XYZ_C_YELLOW}" "${XYZ_C_RESET}" "$*" >&2; }
xyz_error() { printf '%s[ERROR]%s %s\n' "${XYZ_C_RED}" "${XYZ_C_RESET}" "$*" >&2; }
xyz_step() { printf '%s==>%s %s\n' "${XYZ_C_CYAN}" "${XYZ_C_RESET}" "$*"; }
# --- args / init ------------------------------------------------------------
XYZ_ARGS=()
XYZ_YES=0
XYZ_DRY_RUN=0
xyz_parse_global_args() {
local filtered=()
local arg
for arg in "$@"; do
case "${arg}" in
-y|--yes)
XYZ_YES=1
;;
--lang=zh|zh)
XYZ_LANG="zh"
;;
--lang=en|en)
XYZ_LANG="en"
;;
--dry-run)
XYZ_DRY_RUN=1
;;
--no-color)
XYZ_NO_COLOR=1
XYZ_C_RESET=""; XYZ_C_BOLD=""; XYZ_C_DIM=""; XYZ_C_RED=""
XYZ_C_GREEN=""; XYZ_C_YELLOW=""; XYZ_C_CYAN=""
;;
--help|-h)
XYZ_HELP=1
filtered+=("${arg}")
;;
*)
filtered+=("${arg}")
;;
esac
done
XYZ_ARGS=("${filtered[@]+"${filtered[@]}"}")
if [[ "${YES:-}" =~ ^(1|yes|true|YES)$ || "${XYZ_ASSUME_YES:-}" == "1" ]]; then
XYZ_YES=1
fi
# Exported so individual scripts can read flags set here.
export XYZ_ARGS XYZ_YES XYZ_LANG XYZ_HELP="${XYZ_HELP:-}" XYZ_DRY_RUN="${XYZ_DRY_RUN:-0}"
export XYZ_NO_COLOR="${XYZ_NO_COLOR:-0}"
if declare -F xyz_ui_init >/dev/null; then xyz_ui_init; fi
}
xyz_banner() {
local title="${XYZ_TITLE:-$XYZ_NAME}"
printf '\n%s%sxyz.sh/%s%s v%s\n' "${XYZ_C_BOLD}" "${XYZ_C_CYAN}" "${XYZ_NAME}" "${XYZ_C_RESET}" "${XYZ_VERSION}"
printf '%s\n' "${XYZ_C_DIM}----------------------------------------${XYZ_C_RESET}"
printf ' %s: %s/%s\n' "$(xyz_t "Page" "页面")" "${XYZ_BASE}" "${XYZ_NAME}"
printf ' %s: %s/%s.sh\n' "$(xyz_t "Raw" "源码")" "${XYZ_BASE}" "${XYZ_NAME}"
if [[ -n "${XYZ_UPSTREAM:-}" ]]; then
printf ' %s: %s\n' "$(xyz_t "Upstream" "上游来源")" "${XYZ_UPSTREAM}"
fi
printf ' %s\n' "$(xyz_t "No telemetry, no hidden actions." "无遥测、无隐藏操作。")"
printf '%s\n\n' "${XYZ_C_DIM}----------------------------------------${XYZ_C_RESET}"
if [[ -n "${title}" && "${title}" != "${XYZ_NAME}" ]]; then
xyz_step "${title}"
fi
}
xyz_init() {
xyz_parse_global_args "$@"
xyz_detect_os
xyz_banner
}
# --- root / OS --------------------------------------------------------------
xyz_is_root() {
[[ "${EUID:-$(id -u)}" -eq 0 ]]
}
xyz_require_root() {
if ! xyz_is_root; then
xyz_error "$(xyz_t \
"This script must be run as root. Try: sudo bash" \
"请使用 root 运行。可尝试:sudo bash")"
exit 1
fi
}
xyz_prefer_root() {
if ! xyz_is_root; then
xyz_warn "$(xyz_t \
"Not running as root; some information or tests may be limited." \
"当前不是 root,部分信息或测试可能不完整。")"
fi
}
XYZ_OS_ID=""
XYZ_OS_LIKE=""
XYZ_OS_VERSION=""
XYZ_OS_FAMILY="" # debian | rhel | unknown
XYZ_OS_PRETTY=""
xyz_detect_os() {
XYZ_OS_ID=""
XYZ_OS_LIKE=""
XYZ_OS_VERSION=""
XYZ_OS_FAMILY="unknown"
XYZ_OS_PRETTY="unknown"
if [[ -r /etc/os-release ]]; then
# shellcheck disable=SC1091
. /etc/os-release
XYZ_OS_ID="${ID:-}"
XYZ_OS_LIKE="${ID_LIKE:-}"
XYZ_OS_VERSION="${VERSION_ID:-}"
XYZ_OS_PRETTY="${PRETTY_NAME:-$XYZ_OS_ID}"
export XYZ_OS_ID XYZ_OS_LIKE XYZ_OS_VERSION XYZ_OS_FAMILY XYZ_OS_PRETTY
fi
case "${XYZ_OS_ID}" in
debian|ubuntu)
XYZ_OS_FAMILY="debian"
;;
centos|rhel|rocky|almalinux|alma|fedora)
XYZ_OS_FAMILY="rhel"
;;
*)
case " ${XYZ_OS_ID} ${XYZ_OS_LIKE} " in
*debian*|*ubuntu*) XYZ_OS_FAMILY="debian" ;;
*rhel*|*centos*|*fedora*|*rocky*|*alma*) XYZ_OS_FAMILY="rhel" ;;
*) : ;;
esac
;;
esac
}
xyz_os_supported() {
case "${XYZ_OS_ID}" in
debian|ubuntu|centos|rocky|almalinux) return 0 ;;
*) : ;;
esac
case " ${XYZ_OS_LIKE} " in
*debian*|*ubuntu*|*rhel*|*centos*|*rocky*|*alma*) return 0 ;;
*) : ;;
esac
return 1
}
xyz_require_supported_os() {
xyz_detect_os
if ! xyz_os_supported; then
xyz_warn "$(xyz_t \
"Unrecognized distribution: ${XYZ_OS_ID:-unknown} (${XYZ_OS_PRETTY}). Officially supported: Debian, Ubuntu, CentOS, Rocky, AlmaLinux." \
"未能识别的发行版:${XYZ_OS_ID:-unknown}(${XYZ_OS_PRETTY})。官方支持:Debian、Ubuntu、CentOS、Rocky、AlmaLinux。")"
if ! xyz_confirm "$(xyz_t "Continue anyway?" "仍然继续?")"; then
exit 1
fi
else
xyz_info "$(xyz_t "Detected OS:" "检测到系统:") ${XYZ_OS_PRETTY} (${XYZ_OS_FAMILY})"
fi
}
# --- packages / commands ----------------------------------------------------
xyz_need_cmd() {
command -v "$1" >/dev/null 2>&1
}
xyz_pkg_install() {
xyz_detect_os
if (( $# == 0 )); then
return 0
fi
case "${XYZ_OS_FAMILY}" in
debian)
export DEBIAN_FRONTEND=noninteractive
apt-get update -y || xyz_warn "$(xyz_t "apt-get update reported errors (a repository may be unreachable); trying to install anyway." "apt-get update 报错(可能有软件源无法访问),仍尝试安装。")"
apt-get install -y --no-install-recommends "$@"
;;
rhel)
if xyz_need_cmd dnf; then
dnf install -y "$@"
elif xyz_need_cmd yum; then
yum install -y "$@"
else
xyz_error "$(xyz_t "Neither dnf nor yum is available." "找不到 dnf 或 yum。")"
exit 1
fi
;;
*)
xyz_error "$(xyz_t "Cannot install packages on this OS automatically." "无法在此系统上自动安装软件包。")"
exit 1
;;
esac
}
xyz_ensure_cmds() {
local pkg
local missing=()
for pkg in "$@"; do
if ! xyz_need_cmd "${pkg}"; then
missing+=("${pkg}")
fi
done
if ((${#missing[@]} > 0)); then
xyz_info "$(xyz_t "Installing missing commands:" "正在安装缺失命令:") ${missing[*]}"
xyz_pkg_install "${missing[@]}"
fi
}
# --- confirmation (safe with curl | bash) -----------------------------------
# A readable /dev/tty node is not enough: in containers or curl|bash without a
# controlling terminal, open() fails with ENXIO ("No such device or address").
# [[ -r /dev/tty ]] is true in that case and must not be used as the check.
xyz_open_tty() {
# Opens /dev/tty into XYZ_TTY_FD if it is a real terminal. Caller must close.
local fd
XYZ_TTY_FD=""
# Brace group so a failed open cannot leak "No such device or address".
if { exec {fd}<>/dev/tty; } 2>/dev/null && [[ -t "${fd}" ]]; then
XYZ_TTY_FD="${fd}"
return 0
fi
if [[ -n "${fd:-}" ]]; then
exec {fd}>&- 2>/dev/null || true
fi
return 1
}
xyz_close_tty() {
if [[ -n "${XYZ_TTY_FD:-}" ]]; then
exec {XYZ_TTY_FD}>&- 2>/dev/null || true
XYZ_TTY_FD=""
fi
}
xyz_confirm() {
local prompt="$1"
if [[ "${XYZ_YES}" == "1" ]]; then
xyz_info "$(xyz_t "Auto-confirmed (-y / YES=1):" "已自动确认(-y / YES=1):") ${prompt}"
return 0
fi
local reply=""
if xyz_open_tty; then
printf '%s [y/N] ' "${prompt}" >&"${XYZ_TTY_FD}"
# shellcheck disable=SC2162
read -r reply <&"${XYZ_TTY_FD}" || true
xyz_close_tty
else
xyz_warn "$(xyz_t \
"No TTY available for confirmation. Re-run with -y or YES=1 if you accept." \
"没有可用的终端来确认。若你已了解并同意,请加 -y 或 YES=1 重试。")"
return 1
fi
case "${reply}" in
y|Y|yes|YES|Yes) return 0 ;;
*) return 1 ;;
esac
}
# --- download helpers -------------------------------------------------------
# Create the temp dir in the main shell. xyz_tmpdir is usually called inside
# $(...), a subshell, so creating it (and its EXIT trap) there would delete the
# directory as soon as the subshell returned.
xyz_init_tmpdir() {
if [[ -z "${XYZ_TMPDIR:-}" || ! -d "${XYZ_TMPDIR}" ]]; then
XYZ_TMPDIR="$(mktemp -d "${TMPDIR:-/tmp}/xyzsh.XXXXXX")"
# shellcheck disable=SC2064
trap "rm -rf '${XYZ_TMPDIR}'" EXIT
fi
}
xyz_tmpdir() {
if [[ -z "${XYZ_TMPDIR:-}" || ! -d "${XYZ_TMPDIR}" ]]; then
xyz_error "internal: temp dir not initialised"
exit 1
fi
printf '%s' "${XYZ_TMPDIR}"
}
xyz_fetch() {
# xyz_fetch URL DEST
local url="$1"
local dest="$2"
xyz_info "$(xyz_t "Downloading" "正在下载"): ${url}"
xyz_info "$(xyz_t "Saving to" "保存到"): ${dest}"
if xyz_need_cmd curl; then
curl -fsSL --connect-timeout 20 --max-time 180 --retry 2 --retry-delay 1 \
-o "${dest}" "${url}"
elif xyz_need_cmd wget; then
wget -q --timeout=60 -O "${dest}" "${url}"
else
xyz_error "$(xyz_t "Need curl or wget to download files." "需要 curl 或 wget 才能下载文件。")"
exit 1
fi
if [[ ! -s "${dest}" ]]; then
xyz_error "$(xyz_t "Download failed or file is empty:" "下载失败或文件为空:") ${url}"
exit 1
fi
if xyz_need_cmd sha256sum; then
xyz_info "SHA256: $(sha256sum "${dest}" | awk '{print $1}')"
elif xyz_need_cmd shasum; then
xyz_info "SHA256: $(shasum -a 256 "${dest}" | awk '{print $1}')"
fi
}
xyz_run_upstream() {
# xyz_run_upstream URL [args...]
# Downloads an official installer, shows the URL and a short preview, then
# runs it only after confirmation (unless -y / YES=1).
local url="$1"
shift
local dest
xyz_init_tmpdir
dest="$(xyz_tmpdir)/upstream.sh"
xyz_fetch "${url}" "${dest}"
chmod +x "${dest}"
xyz_info "$(xyz_t "Preview (first 20 lines):" "预览(前 20 行):")"
sed -n '1,20p' "${dest}" || true
printf '%s\n' "${XYZ_C_DIM}...${XYZ_C_RESET}"
# Default --dry-run: verify the download and preview, do not execute.
# Scripts that forward --dry-run to upstream (e.g. docker) set
# XYZ_FORWARD_DRY_RUN=1 so the official script still runs with that flag.
if [[ "${XYZ_DRY_RUN:-0}" == "1" && "${XYZ_FORWARD_DRY_RUN:-0}" != "1" ]]; then
xyz_info "$(xyz_t \
"Dry-run: official script downloaded and previewed; not executing it." \
"演练模式:已下载并预览官方脚本,不会执行。")"
return 0
fi
if ! xyz_confirm "$(xyz_t \
"Run this official upstream script?" \
"运行这份官方上游脚本?")"; then
xyz_error "$(xyz_t "Aborted by user." "已取消。")"
exit 1
fi
xyz_step "$(xyz_t "Executing upstream script" "正在执行上游脚本")"
# Never let the upstream script inherit our stdin: under `curl | bash` that
# is the rest of this very script. Give it the terminal if there is one,
# otherwise /dev/null. Interactive installers set XYZ_UPSTREAM_NEEDS_TTY=1.
if xyz_open_tty; then
local tty_fd="${XYZ_TTY_FD}"
XYZ_TTY_FD=""
bash "${dest}" "$@" <&"${tty_fd}"
local rc=$?
exec {tty_fd}>&- 2>/dev/null || true
return "${rc}"
fi
if [[ "${XYZ_UPSTREAM_NEEDS_TTY:-0}" == "1" ]]; then
xyz_error "$(xyz_t \
"This official installer is interactive and needs a terminal. Log in with SSH and run: bash <(curl -fsSL ${XYZ_BASE}/${XYZ_NAME})" \
"这个官方安装脚本需要交互,必须在终端里运行。请用 SSH 登录后执行:bash <(curl -fsSL ${XYZ_BASE}/${XYZ_NAME})")"
exit 1
fi
bash "${dest}" "$@" </dev/null
}
# --- small shared helpers ----------------------------------------------------
xyz_strip_ansi() {
sed -e 's/\x1b\[[0-9;?]*[A-Za-z]//g' -e 's/\r//g'
}
# Effective SSH port: sshd -T (what sshd really uses) > config files > env > 22.
xyz_effective_ssh_port() {
local port=""
if xyz_need_cmd sshd; then
port="$(sshd -T 2>/dev/null | awk '$1=="port" {print $2; exit}' || true)"
fi
if [[ -z "${port}" && -d /etc/ssh/sshd_config.d ]]; then
port="$(cat /etc/ssh/sshd_config.d/*.conf 2>/dev/null | awk 'tolower($1)=="port" {print $2; exit}' || true)"
fi
if [[ -z "${port}" && -f /etc/ssh/sshd_config ]]; then
port="$(awk 'tolower($1)=="port" {print $2; exit}' /etc/ssh/sshd_config || true)"
fi
if [[ -z "${port}" && -n "${SSH_CONNECTION:-}" ]]; then
port="$(printf '%s' "${SSH_CONNECTION}" | awk '{print $4}')"
fi
printf '%s' "${port:-22}"
}
xyz_has_systemd() {
[[ -d /run/systemd/system ]] && xyz_need_cmd systemctl
}
# Back up a file once per run as FILE.xyz-bak-YYYYmmddHHMMSS and print the path.
xyz_backup_file() {
local f="$1"
local bak
bak="${f}.xyz-bak-$(date +%Y%m%d%H%M%S)"
if [[ -e "${f}" ]]; then
cp -a "${f}" "${bak}"
printf '%s' "${bak}"
fi
}
# --- misc -------------------------------------------------------------------
xyz_usage_exit() {
if [[ "${1:-}" != "" ]]; then
printf '%s\n' "$1"
fi
exit 0
}
XYZ_NAME="clean"
# xyz.sh/clean — safe disk cleanup. Shows usage before and after.
# Covers package caches, journal vacuum, old snap revisions, /tmp leftovers
# and large log files. Docker prune only with --docker. Old kernels only
# when listed (never the running one), and only with --kernels.
# --dry-run lists only. Confirmation is required unless -y.
#
# Usage:
# curl -fsSL xyz.sh/clean | bash
# curl -fsSL xyz.sh/clean | bash -s -- --dry-run
# curl -fsSL xyz.sh/clean | bash -s -- -y
# curl -fsSL xyz.sh/clean | bash -s -- -y --docker --kernels
#
# Supported: Debian, Ubuntu, CentOS, Rocky, AlmaLinux. Root required.
# No telemetry.
set -euo pipefail
if [[ -z "${XYZ_COMMON_LOADED:-}" ]]; then
_xyz_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "${_xyz_dir}/lib/common.sh" ]]; then
# shellcheck source=lib/common.sh
source "${_xyz_dir}/lib/common.sh"
else
echo "xyz.sh: missing lib/common.sh" >&2
exit 1
fi
fi
XYZ_NAME="${XYZ_NAME:-clean}"
XYZ_TITLE="$(xyz_t "Safe disk cleanup" "安全清理磁盘")"
xyz_init "$@"
DO_DOCKER=0
DO_KERNELS=0
DO_AUTOREMOVE=0
for arg in "${XYZ_ARGS[@]+"${XYZ_ARGS[@]}"}"; do
case "${arg}" in
--docker) DO_DOCKER=1 ;;
--kernels|--old-kernels) DO_KERNELS=1 ;;
--autoremove) DO_AUTOREMOVE=1 ;;
--help|-h) XYZ_HELP=1 ;;
*)
xyz_error "$(xyz_t "Unknown argument:" "未知参数:") ${arg}"
exit 1
;;
esac
done
if [[ "${XYZ_HELP:-}" == "1" ]]; then
cat <<HINT
$(xyz_t "Usage:" "用法:")
curl -fsSL xyz.sh/clean | bash -s -- --dry-run
curl -fsSL xyz.sh/clean | bash -s -- -y
curl -fsSL xyz.sh/clean | bash -s -- -y --docker --kernels
$(xyz_t "Default (safe) actions:" "默认(偏安全)的操作:")
- $(xyz_t "Package manager caches: apt clean / yum or dnf clean all" "软件源缓存:apt clean / yum 或 dnf clean all")
- $(xyz_t "systemd journal vacuum to 100M" "把 systemd 日志真空到 100M")
- $(xyz_t "Remove disabled (old) snap revisions, never the active one" "删除已禁用的旧 snap 修订,不动正在使用的")
- $(xyz_t "List leftover files in /tmp older than 7 days (not in use) and remove them" "列出并删除 /tmp 中超过 7 天且未被占用的残留文件")
- $(xyz_t "List log files under /var/log larger than 50M; truncate rotated *.gz / *.old / numbered logs, never the active journal" "列出 /var/log 下大于 50M 的日志;清空已轮转的 *.gz / *.old / 带编号日志,不动正在写入的 journal")
$(xyz_t "Opt-in only:" "需显式打开:")
--docker $(xyz_t "docker system prune -f (unused images, containers, networks; does not use -a/--volumes)" "docker system prune -f(未使用的镜像/容器/网络;不加 -a 或 --volumes)")
--kernels $(xyz_t "remove unused kernels, never the one uname -r is running" "删除未使用的旧内核,永远不会删正在运行的(uname -r)")
--autoremove $(xyz_t "apt autoremove / dnf autoremove (may remove packages you still want)" "apt autoremove / dnf autoremove(可能卸掉你还想留的包)")
$(xyz_t "--dry-run only lists what would be cleaned; nothing is deleted." "--dry-run 只列出将清理的内容,不删除任何东西。")
$(xyz_t "A confirmation is required unless you pass -y." "除非加上 -y,否则会先征求确认。")
HINT
exit 0
fi
xyz_require_root
xyz_require_supported_os
RUNNING_KERNEL="$(uname -r)"
human() {
# human BYTES
awk -v b="${1:-0}" 'BEGIN {
if (b < 1024) { printf "%d B", b; exit }
split("K M G T", u, " "); n = b
for (i = 0; n >= 1024 && i < 4; i++) n = n / 1024
printf "%.1f %sB", n, u[i]
}'
}
disk_used_bytes() {
df -P -B1 / 2>/dev/null | awk 'NR==2 {print $3}'
}
disk_line() {
df -hP / 2>/dev/null | awk 'NR==2 {printf "%s used / %s total (%s), %s available", $3, $2, $5, $4}'
}
size_of() {
local p="$1"
if [[ -f "${p}" ]]; then
wc -c < "${p}" | tr -d ' '
elif [[ -d "${p}" ]]; then
du -sb "${p}" 2>/dev/null | awk '{print $1}'
else
printf '0'
fi
}
PLAN=()
add_plan() {
PLAN+=("$1")
}
run_or_say() {
# run_or_say DESCRIPTION COMMAND...
local desc="$1"
shift
if [[ "${XYZ_DRY_RUN:-0}" == "1" ]]; then
xyz_info "$(xyz_t "Would run:" "将执行:") ${desc}"
return 0
fi
xyz_info "${desc}"
if "$@"; then
return 0
fi
xyz_warn "$(xyz_t "Command failed (continuing):" "命令失败(继续):") ${desc}"
return 0
}
# ---- inspect ----------------------------------------------------------------
xyz_step "$(xyz_t "Current disk usage" "当前磁盘占用")"
xyz_info "$(disk_line)"
BEFORE="$(disk_used_bytes || printf 0)"
# Package caches
pkg_bytes=0
if xyz_need_cmd apt-get; then
pkg_bytes="$(size_of /var/cache/apt)"
add_plan "apt-get clean ($(human "${pkg_bytes}"))"
if [[ "${DO_AUTOREMOVE}" == "1" ]]; then
add_plan "apt-get autoremove -y ($(xyz_t "opt-in" "需显式打开"))"
fi
elif xyz_need_cmd dnf; then
pkg_bytes="$(size_of /var/cache/dnf)"
add_plan "dnf clean all ($(human "${pkg_bytes}"))"
if [[ "${DO_AUTOREMOVE}" == "1" ]]; then
add_plan "dnf autoremove -y ($(xyz_t "opt-in" "需显式打开"))"
fi
elif xyz_need_cmd yum; then
pkg_bytes="$(size_of /var/cache/yum)"
add_plan "yum clean all ($(human "${pkg_bytes}"))"
fi
# journal
if xyz_need_cmd journalctl && [[ -d /run/systemd/system || -d /var/log/journal ]]; then
jsize="$(journalctl --disk-usage 2>/dev/null | grep -oE '[0-9.]+[KMGT]?i?B' | tail -1 || true)"
add_plan "journalctl --vacuum-size=100M (${jsize:-?})"
else
add_plan "$(xyz_t "journalctl / journal not present; skip vacuum" "未检测到 journalctl / journal,跳过 vacuum")"
fi
# snap old revisions
SNAP_REVS=()
if xyz_need_cmd snap; then
while IFS= read -r line; do
# name version rev tracking publisher notes
name="$(printf '%s' "${line}" | awk '{print $1}')"
rev="$(printf '%s' "${line}" | awk '{print $3}')"
notes="$(printf '%s' "${line}" | awk '{print $NF}')"
if [[ "${notes}" == *disabled* && -n "${name}" && -n "${rev}" ]]; then
SNAP_REVS+=("${name}|${rev}")
add_plan "snap remove ${name} --revision=${rev}"
fi
done < <(snap list --all 2>/dev/null | awk 'NR>1' || true)
if [[ "${#SNAP_REVS[@]}" -eq 0 ]]; then
add_plan "$(xyz_t "No disabled snap revisions" "没有可删除的旧 snap 版本")"
fi
else
add_plan "$(xyz_t "snap is not installed; skip old revisions" "未安装 snap,跳过旧版本清理")"
fi
# /tmp leftovers older than 7 days, not directories that are mount points, skip lost+found
TMP_FILES=()
if [[ -d /tmp ]]; then
while IFS= read -r -d '' f; do
TMP_FILES+=("${f}")
done < <(find /tmp -xdev -ignore_readdir_race -type f -mtime +7 -not -path '/tmp/systemd-*' -print0 2>/dev/null || true)
if [[ "${#TMP_FILES[@]}" -gt 0 ]]; then
tsz=0
for f in "${TMP_FILES[@]}"; do
tsz=$((tsz + $(size_of "${f}")))
done
add_plan "$(xyz_t "Remove ${#TMP_FILES[@]} /tmp files older than 7 days" "删除 /tmp 中 ${#TMP_FILES[@]} 个超过 7 天的文件") ($(human "${tsz}"))"
else
add_plan "$(xyz_t "No /tmp files older than 7 days" "没有超过 7 天的 /tmp 残留文件")"
fi
fi
# large rotated logs
LOG_FILES=()
if [[ -d /var/log ]]; then
while IFS= read -r -d '' f; do
case "${f}" in
*.gz|*.xz|*.bz2|*.old|*.[0-9]) LOG_FILES+=("${f}") ;;
*) ;;
esac
done < <(find /var/log -xdev -ignore_readdir_race -type f -size +50M -print0 2>/dev/null || true)
if [[ "${#LOG_FILES[@]}" -gt 0 ]]; then
lsz=0
for f in "${LOG_FILES[@]}"; do
lsz=$((lsz + $(size_of "${f}")))
done
add_plan "$(xyz_t "Remove ${#LOG_FILES[@]} rotated logs larger than 50M under /var/log" "删除 /var/log 下 ${#LOG_FILES[@]} 个大于 50M 的已轮转日志") ($(human "${lsz}"))"
else
add_plan "$(xyz_t "No rotated /var/log files larger than 50M" "没有大于 50M 的已轮转日志")"
fi
fi
# docker (opt-in)
if [[ "${DO_DOCKER}" == "1" ]]; then
if xyz_need_cmd docker; then
add_plan "docker system prune -f ($(xyz_t "unused images/containers/networks only, no -a or volumes" "仅未使用的镜像/容器/网络,不加 -a 或 volumes"))"
else
xyz_warn "$(xyz_t "--docker was set but docker is not installed; skipping." "已指定 --docker,但未安装 docker,已跳过。")"
fi
fi
# kernels (opt-in, never the running one)
KERNEL_PKGS=()
if [[ "${DO_KERNELS}" == "1" ]]; then
if xyz_need_cmd dpkg; then
while IFS= read -r pkg; do
[[ -z "${pkg}" ]] && continue
# package names like linux-image-5.4.0-109-generic
ver="${pkg#linux-image-}"
ver="${ver#linux-image-unsigned-}"
if [[ "${ver}" == "${RUNNING_KERNEL}" || "${pkg}" == *"${RUNNING_KERNEL}"* ]]; then
xyz_info "$(xyz_t "Keeping the running kernel package:" "保留正在运行的内核包:") ${pkg} (${RUNNING_KERNEL})"
continue
fi
KERNEL_PKGS+=("${pkg}")
add_plan "apt-get purge -y ${pkg} ($(xyz_t "not the running kernel" "不是正在运行的内核") ${RUNNING_KERNEL})"
done < <(dpkg-query -W -f='${Package}\n' 'linux-image-*' 2>/dev/null | grep -E '^linux-image-[0-9]' | grep -v -- '-dbg$' || true)
elif xyz_need_cmd rpm; then
while IFS= read -r pkg; do
[[ -z "${pkg}" ]] && continue
if rpm -q --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' "${pkg}" 2>/dev/null | grep -qx "${RUNNING_KERNEL}"; then
xyz_info "$(xyz_t "Keeping the running kernel package:" "保留正在运行的内核包:") ${pkg} (${RUNNING_KERNEL})"
continue
fi
if [[ "${pkg}" == *"${RUNNING_KERNEL}"* ]]; then
xyz_info "$(xyz_t "Keeping the running kernel package:" "保留正在运行的内核包:") ${pkg} (${RUNNING_KERNEL})"
continue
fi
KERNEL_PKGS+=("${pkg}")
add_plan "yum/dnf remove -y ${pkg} ($(xyz_t "not the running kernel" "不是正在运行的内核") ${RUNNING_KERNEL})"
done < <(rpm -qa 'kernel-core' 'kernel' 'kernel-default' 2>/dev/null || true)
fi
if [[ "${#KERNEL_PKGS[@]}" -eq 0 ]]; then
add_plan "$(xyz_t "No unused kernel packages found (running: ${RUNNING_KERNEL})" "没有发现可删除的旧内核(正在运行:${RUNNING_KERNEL})")"
fi
fi
xyz_step "$(xyz_t "Cleanup plan" "清理计划")"
if [[ "${#PLAN[@]}" -eq 0 ]]; then
xyz_info "$(xyz_t "Nothing obvious to clean." "没有明显可清理的内容。")"
else
i=1
for item in "${PLAN[@]}"; do
printf ' %2d. %s\n' "${i}" "${item}"
i=$((i + 1))
done
fi
if [[ "${DO_DOCKER}" != "1" || "${DO_KERNELS}" != "1" ]]; then
xyz_info "$(xyz_t "Optional (not in this run unless flagged): --docker, --kernels, --autoremove" "未加开关则不执行:--docker、--kernels、--autoremove")"
fi
if [[ "${XYZ_DRY_RUN:-0}" == "1" ]]; then
xyz_info "$(xyz_t "Dry-run: nothing was deleted." "演练模式:没有删除任何东西。")"
xyz_info "$(xyz_t "Disk still:" "磁盘仍为:") $(disk_line)"
exit 0
fi
if ! xyz_confirm "$(xyz_t "Proceed with the cleanup above?" "按上面的计划执行清理?")"; then
xyz_error "$(xyz_t "Aborted by user." "已取消。")"
exit 1
fi
# ---- execute ----------------------------------------------------------------
if xyz_need_cmd apt-get; then
run_or_say "apt-get clean" apt-get clean
if [[ "${DO_AUTOREMOVE}" == "1" ]]; then
run_or_say "apt-get autoremove -y" apt-get -y autoremove
fi
elif xyz_need_cmd dnf; then
run_or_say "dnf clean all" dnf clean all
if [[ "${DO_AUTOREMOVE}" == "1" ]]; then
run_or_say "dnf autoremove -y" dnf -y autoremove
fi
elif xyz_need_cmd yum; then
run_or_say "yum clean all" yum clean all
fi
if xyz_need_cmd journalctl && [[ -d /run/systemd/system || -d /var/log/journal ]]; then
run_or_say "journalctl --vacuum-size=100M" journalctl --vacuum-size=100M
fi
for pair in "${SNAP_REVS[@]+"${SNAP_REVS[@]}"}"; do
name="${pair%%|*}"
rev="${pair##*|}"
run_or_say "snap remove ${name} --revision=${rev}" snap remove "${name}" --revision="${rev}"
done
for f in "${TMP_FILES[@]+"${TMP_FILES[@]}"}"; do
# skip if opened (best-effort, lsof may be missing)
if xyz_need_cmd lsof && lsof -- "${f}" >/dev/null 2>&1; then
xyz_info "$(xyz_t "Skipping in-use file:" "跳过正在使用的文件:") ${f}"
continue
fi
rm -f -- "${f}" 2>/dev/null || true
done
if [[ "${#TMP_FILES[@]}" -gt 0 ]]; then
xyz_info "$(xyz_t "Removed stale /tmp files (or skipped in-use ones)." "已删除过期的 /tmp 文件(占用中的已跳过)。")"
fi
for f in "${LOG_FILES[@]+"${LOG_FILES[@]}"}"; do
rm -f -- "${f}" 2>/dev/null || true
done
if [[ "${#LOG_FILES[@]}" -gt 0 ]]; then
xyz_info "$(xyz_t "Removed oversized rotated logs." "已删除体积过大的已轮转日志。")"
fi
if [[ "${DO_DOCKER}" == "1" ]] && xyz_need_cmd docker; then
run_or_say "docker system prune -f" docker system prune -f
fi
if [[ "${DO_KERNELS}" == "1" && "${#KERNEL_PKGS[@]}" -gt 0 ]]; then
for pkg in "${KERNEL_PKGS[@]}"; do
if [[ "${pkg}" == *"${RUNNING_KERNEL}"* ]]; then
xyz_warn "$(xyz_t "Refusing to remove the running kernel:" "拒绝删除正在运行的内核:") ${pkg}"
continue
fi
if xyz_need_cmd apt-get; then
run_or_say "apt-get purge -y ${pkg}" apt-get purge -y "${pkg}"
elif xyz_need_cmd dnf; then
run_or_say "dnf remove -y ${pkg}" dnf remove -y "${pkg}"
elif xyz_need_cmd yum; then
run_or_say "yum remove -y ${pkg}" yum remove -y "${pkg}"
fi
done
fi
xyz_step "$(xyz_t "Disk usage after cleanup" "清理后的磁盘占用")"
xyz_info "$(disk_line)"
AFTER="$(disk_used_bytes || printf 0)"
if [[ "${BEFORE}" =~ ^[0-9]+$ && "${AFTER}" =~ ^[0-9]+$ ]]; then
if (( AFTER < BEFORE )); then
SAVED=$((BEFORE - AFTER))
xyz_info "$(xyz_t "Freed (approximate, from df):" "大约释放(来自 df):") $(human "${SAVED}")"
else
xyz_info "$(xyz_t "df did not show a drop; some caches may still be reserved by the filesystem." "df 未显示下降;部分缓存可能仍被文件系统预留。")"
fi
fi
xyz_info "$(xyz_t "Cleanup finished." "清理完成。")"
推荐 VPS
以下为占位展示,尚未接入任何商家或联盟链接,也没有可点击的购买地址。上线推广前会再填入真实套餐与合规的返佣链接。
推荐套餐即将接入
目前还没有已上线的商家或联盟链接,因此不展示空的购买入口。接入真实套餐后会显示在这里,链接会标明「推广链接」。
查优惠码 · youhuima.cc — 优惠码也可在 youhuima.cc 查找,是否可用以商家规则为准。