Skip to content

Instantly share code, notes, and snippets.

@justincbagley
Created October 26, 2021 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justincbagley/2246075e03676de9fd37a75a49bdf99e to your computer and use it in GitHub Desktop.
Save justincbagley/2246075e03676de9fd37a75a49bdf99e to your computer and use it in GitHub Desktop.
unzipper - a shell function for unzipping files and folders to add to your path on macOS

unzipper

A useful function to add to your ~/.bash_profile or ~/.bashrc file on macOS that automates custom unzipping of regular-zipped or gzipped files and folders on Mac.

This is a companion function/script to my zipper function posted in a Gist here.

Add in your path as a full shell script by copying all below and saving into a file named unzipper located in your $PATH (e.g. /usr/bin), or copy and paste just the function into ~/.bash_profile or ~/.bashrc then restart Terminal.

#!/bin/sh

# unzipper

## Usage: zipper "$1", where "$1" is a zipped or gzipped file or folder to _unzip_.

unzipper () {
	MY_FILE="$1"
	FILE_B_OUT="$(file -b "$1")";
	MY_FILE_CLEAN="$(basename "$1")";
#
	MY_ZIP_TEST="$(basename "$MY_FILE" | grep ".zip$" | wc -l | sed 's/\ //g')";
	MY_GZIP_TEST="$(basename "$MY_FILE" | grep ".gzip$" | wc -l | sed 's/\ //g')";
	MY_GZ_TEST="$(basename "$MY_FILE" | grep ".gz$" | wc -l | sed 's/\ //g')";
	MY_TAR_GZ_TEST="$(basename "$MY_FILE" | grep ".tar.gz$" | wc -l | sed 's/\ //g')";
#
	if [[ "$FILE_B_OUT" != "directory" ]]; then

		# .zip file:
		if [[ "$MY_ZIP_TEST" = "1" ]] && [[ "$MY_GZIP_TEST" = "0" ]] && [[ "$MY_GZ_TEST" = "0" ]] && [[ "$MY_TAR_GZ_TEST" = "0" ]]; then
			echo "Unzipping .zip file named ${MY_FILE_CLEAN} ..."
			MACOSX_FOLDER_CHECK="$(ls -d  ./__MACOSX/ | wc -l | sed 's/\ //g')";
			if [[ "$MACOSX_FOLDER_CHECK" = "0" ]]; then
				unzip "$MY_FILE_CLEAN" ;
				MACOSX_FOLDER_CHECK="$(ls -d  ./__MACOSX/ | wc -l | sed 's/\ //g')";
				if [[ "$MACOSX_FOLDER_CHECK" != "0" ]]; then
					rm -rf ./__MACOSX/  ;
				fi
			fi
		fi

		# .gz file:
		if [[ "$MY_ZIP_TEST" = "0" ]] && [[ "$MY_GZIP_TEST" = "0" ]] && [[ "$MY_GZ_TEST" = "1" ]] && [[ "$MY_TAR_GZ_TEST" = "0" ]]; then
			echo "Unzipping .gz file named ${MY_FILE_CLEAN} ..."
			# Unzip gzipped (.gz) file while keeping original .gz file:
			# usage: gzip -dk file.gz
			# gzip -dk "$MY_FILE_CLEAN";
			#
			# Unzip gzipped (.gz) file while removing original .gz file:
			gzip -d "$MY_FILE_CLEAN";
		fi

		# .tar.gz file:
		if [[ "$MY_ZIP_TEST" = "0" ]] && [[ "$MY_GZIP_TEST" = "0" ]] && [[ "$MY_GZ_TEST" = "1" ]] && [[ "$MY_TAR_GZ_TEST" = "1" ]]; then
			echo "Unzipping .tar.gz file (gzipped tarball) named ${MY_FILE_CLEAN} ..."
			tar -xf "$MY_FILE_CLEAN";
		fi
		
	fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment