#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 archive.tar[.gz|.zst] destination [--force]" >&2 } if [[ $# -lt 2 ]]; then usage exit 2 fi archive=$1 destination=$2 shift 2 force=0 for arg in "$@"; do case "$arg" in --force) force=1 ;; *) echo "Неизвестный аргумент: $arg" >&2 usage exit 2 ;; esac done if [[ ! -f "$archive" ]]; then echo "Архив не найден: $archive" >&2 exit 1 fi command -v tar >/dev/null 2>&1 || { echo "Нужен tar" >&2; exit 1; } list_plain() { case "$archive" in *.tar.zst|*.tzst) command -v zstd >/dev/null 2>&1 || { echo "Нужен zstd" >&2; exit 1; } zstd -dc -- "$archive" | tar -tf - ;; *) tar -tf "$archive" ;; esac } list_verbose() { case "$archive" in *.tar.zst|*.tzst) zstd -dc -- "$archive" | tar -tvf - ;; *) tar -tvf "$archive" ;; esac } unsafe=0 while IFS= read -r entry; do case "$entry" in /*|..|../*|*/../*|*/..) echo "Небезопасный путь: $entry" >&2 unsafe=1 ;; esac done < <(list_plain) while IFS= read -r line; do case "${line:0:1}" in l|h) echo "Ссылка в архиве не поддерживается: $line" >&2 unsafe=1 ;; esac done < <(list_verbose) if [[ $unsafe -ne 0 ]]; then echo "Распаковка отменена." >&2 exit 2 fi if [[ -e "$destination" ]]; then if [[ ! -d "$destination" ]]; then echo "Цель не является папкой: $destination" >&2 exit 1 fi destination_abs=$(cd -- "$destination" && pwd -P) if [[ -n "$(ls -A "$destination_abs")" && $force -eq 0 ]]; then echo "Папка не пуста: $destination. Используйте --force" >&2 exit 1 fi fi mkdir -p -- "$destination" case "$archive" in *.tar.zst|*.tzst) zstd -dc -- "$archive" | tar -xf - -C "$destination" ;; *) tar -xf "$archive" -C "$destination" ;; esac echo "Распаковано в $destination"