← Back
Archive a directory
Packs a directory into a timestamped tar.gz, excluding node_modules, .git, caches and dist. No root needed.
Runs as any user
One-line run
curl -fsSL https://www.moiu.cn/scripts/dir-backup.sh | bashSource
#!/usr/bin/env bash
# 目录打包备份
#
# 把指定目录打成一个带时间戳的 tar.gz,自动排除缓存与依赖目录。
# 不需要 root(除非目录本身要 root 才能读)。
# 用法:bash dir-backup.sh /var/www
# bash dir-backup.sh /var/www /opt/backup
set -e
SRC="$1"
DEST="$2"
if [ -z "$SRC" ]; then
echo '用法:bash dir-backup.sh <要备份的目录> [输出目录]'
exit 1
fi
if [ ! -d "$SRC" ]; then
echo "[!] 目录不存在:$SRC"
exit 1
fi
PARENT=$(cd "$SRC/.." && pwd)
NAME=$(basename "$(cd "$SRC" && pwd)")
if [ -z "$DEST" ]; then
DEST="$PARENT"
fi
mkdir -p "$DEST"
STAMP=$(date +%Y%m%d_%H%M%S)
OUT="$DEST/$NAME-$STAMP.tar.gz"
echo "====== 备份 $SRC ======"
echo "[*] 输出:$OUT"
tar \
--exclude='node_modules' \
--exclude='.git' \
--exclude='.cache' \
--exclude='dist' \
--exclude='__pycache__' \
-czf "$OUT" \
-C "$PARENT" "$NAME"
echo ''
echo '====== 完成 ======'
ls -lh "$OUT"
echo "[*] 内含 $(tar -tzf "$OUT" | wc -l) 个条目"
