function extract if test (count $argv) -lt 1 echo "Usage: extract [output_directory]" return 1 end set archives $argv set output_dir "." set use_custom_dir 0 # If exactly 2 args and second is a directory (or doesn't exist yet), treat it as output dir if test (count $argv) -eq 2 set maybe_dir $argv[2] if test -d "$maybe_dir"; or not test -e "$maybe_dir" set output_dir "$maybe_dir" mkdir -p "$output_dir" set archives $argv[1] set use_custom_dir 1 end end # Detect multiple archives set multi 0 if test (count $archives) -gt 1 set multi 1 end for archive in $archives if not test -f "$archive" echo "extract: '$archive' is not a valid file" continue end # Determine base name (strip extensions) set base (string replace -r '\.(tar\.gz|tgz|tar\.bz2|tbz2|tar\.xz|txz|gz|bz2|xz|zst|zip|7z|rar)$' '' (basename "$archive")) # Decide target directory if test $multi -eq 1 set target_dir "$base" else if test $use_custom_dir -eq 1 set target_dir "$output_dir" else set target_dir "$base" end mkdir -p "$target_dir" set mime (file --mime-type -b "$archive") switch $mime case 'application/x-tar' tar -xvf "$archive" -C "$target_dir" case 'application/gzip' tar xvzf "$archive" -C "$target_dir" case 'application/x-bzip2' tar xvjf "$archive" -C "$target_dir" case 'application/x-xz' tar xvJf "$archive" -C "$target_dir" case 'application/zstd' tar --zstd -xvf "$archive" -C "$target_dir" case 'application/zip' unzip "$archive" -d "$target_dir" case 'application/x-7z-compressed' 7z x "$archive" -o"$target_dir" case 'application/x-rar' 'application/vnd.rar' unrar x -o+ "$archive" "$target_dir" case '*' echo "extract: unknown file type for '$archive' ($mime)" continue end end end