From 5b5647e0db62c9846c84e6d39f793a51bfe56b60 Mon Sep 17 00:00:00 2001 From: cedric Date: Wed, 4 Jun 2025 16:25:59 +0200 Subject: [PATCH] Better help and error management - Added set -euo pipefail for improved error handling and script safety. - Added --help option and better usage messaging. - Checks for required tools (unzip, unrar, 7z, etc.) before extraction. --- extract | 63 ++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 18 deletions(-) diff --git a/extract b/extract index aacf9df..406dcdf 100644 --- a/extract +++ b/extract @@ -1,19 +1,46 @@ #!/bin/bash -if [ -f $1 ] ; then - case $1 in - *.tar.bz2) tar xjf $1 ;; - *.tar.gz) tar xzf $1 ;; - *.bz2) bunzip2 $1 ;; - *.rar) unrar x $1 ;; - *.gz) gunzip $1 ;; - *.tar) tar xf $1 ;; - *.tbz2) tar xjf $1 ;; - *.tgz) tar xzf $1 ;; - *.zip) unzip $1 ;; - *.Z) uncompress $1;; - *.7z) 7z x $1 ;; - *) echo "'$1' cannot be extracted" ;; - esac - else - echo "'$1' invalid file" - fi \ No newline at end of file +set -euo pipefail +IFS=$'\n\t' + +usage() { + echo "Usage: $0 " + echo "Extract supported archive formats: .tar.gz, .zip, .rar, .7z, etc." +} + +check_command() { + local cmd="$1" + if ! command -v "$cmd" &>/dev/null; then + echo "Error: required command '$cmd' not found." + exit 3 + fi +} + +if [[ $# -eq 0 || "$1" == "--help" ]]; then + usage + exit 0 +fi + +file="$1" + +if [[ ! -f "$file" ]]; then + echo "Error: '$file' is not a valid file." + exit 2 +fi + +case "$file" in + *.tar.bz2) check_command tar; tar xjf "$file" ;; + *.tar.gz) check_command tar; tar xzf "$file" ;; + *.bz2) check_command bunzip2; bunzip2 "$file" ;; + *.rar) check_command unrar; unrar x "$file" ;; + *.gz) check_command gunzip; gunzip "$file" ;; + *.tar) check_command tar; tar xf "$file" ;; + *.tbz2) check_command tar; tar xjf "$file" ;; + *.tgz) check_command tar; tar xzf "$file" ;; + *.zip) check_command unzip; unzip "$file" ;; + *.Z) check_command uncompress; uncompress "$file" ;; + *.7z) check_command 7z; 7z x "$file" ;; + *) + echo "Error: '$file' has an unsupported file extension." + exit 1 + ;; +esac