Last active
July 16, 2021 03:50
-
-
Save subfuzion/57bf9dca1951c3d0da9672d9ae8b97c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Dependencies: sed, grep | |
# | |
# Usage: unjar FILE [DEST] | |
# | |
# - DEST must not already exist (won't overwrite existing contents); | |
# path to DEST will be created. | |
# TODO: add overwrite option | |
# | |
# - If DEST is not provided, defaults to a subdirectory in the current | |
# working directory that will be named after FILE without the extension. | |
# Ex: unjar foo.jar # foo.jar extracted to ./foo | |
# | |
# - If DEST is provided, the path will be created and the jar will | |
# be extracted into it. | |
# Ex: unjar foo.jar /a/b/c # foo.jar extracted into /a/b/c | |
# TODO: add option to extract into final path component based on | |
# the filename | |
# Ex: unjar -X foo.jar /a/b/c # foo.jar extracted into /a/b/c/foo | |
error() { | |
echo "Error: $@" | |
echo "Usage: $(basename $0) FILE [DEST]" | |
exit 1 | |
} | |
# return the file name (including extension) without any path components | |
basename() { | |
printf "$1" | sed 's/^.*\///' | |
} | |
# returns name without an extension (must already be a basename) | |
dropext() { | |
printf "$1" | sed 's/\.[^.]*$//' | |
} | |
strip_trailing_slashes() { | |
printf "$1" | sed 's/[/]*$//' | |
} | |
# If empty arg, return . | |
# If nothing but slashes, return / | |
# If no slashes after stripping all trailing slashes, return . | |
# Otherwise, return everything up until last path component | |
dirname() { | |
if [ -z "$1" ]; then printf '.'; return; fi | |
if ! $(printf "$1" | grep -q '[^/]'); then printf '/'; return; fi | |
local s="$(strip_trailing_slashes $1)" | |
if ! $(printf "$s" | grep -q '/'); then printf '.'; fi | |
printf "$(strip_trailing_slashes $(printf $s | sed 's/[^/]*$//'))" | |
} | |
if [ -z "$1" ]; then error "missing filename"; fi | |
FILE="$1" | |
if ! [ -r "$FILE" ]; then error "can't read file: $FILE"; fi | |
# Need to know full pathname for the file so that it can be | |
# extracted after changing directory to DEST. | |
PATHNAME="$(printf "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")")" | |
# Need to cd to DEST directory before extracting the jar file. | |
DIR="${2:-$(dropext $(basename $FILE))}" | |
if [ -e "$DIR" ]; then error "target directory already exists: $DIR"; fi | |
mkdir -p "$DIR" && cd "$DIR" | |
jar -xf "$PATHNAME" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment