update(README):Clarify `user` directory
[BK-2020-03.git] / user / bkxz
diff --git a/user/bkxz b/user/bkxz
new file mode 100755 (executable)
index 0000000..465369a
--- /dev/null
+++ b/user/bkxz
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+# Date: 2020-04-09T00:09Z
+
+# Author: Steven Baltakatei Sandoval
+
+# Description: Compresses a file or directory using xz at max
+# settings. Saves compressed .tar.xz file in the same directory as the
+# original file.
+
+# Usage: bkxz [ file or dir ]
+
+echoerr() { echo "$@" 1>&2; } # Define error display function.
+
+TARGET="$1" # Identify first argument as target file or directory.
+
+if ! command -v tar >/dev/null 2>&1; then # Check that 'tar' command exists.
+    echoerr "ERROR: Command doesn't exist: tar";
+fi
+
+if ! command -v xz >/dev/null 2>&1; then # check that 'xz' command exist.
+    echoerr "ERROR: Command doesn't exist: xz. Suggestion: Install 'xz-utils' package.";
+    exit 1;
+fi
+
+if ! ( [ -f "$TARGET" ] || [ -d "$TARGET" ] ); then # check that TARGET is a file or dir.
+    echoerr "ERROR: Target is not a file or dir."; exit 1;
+fi
+
+
+TARGET_BASENAME="$(basename "$TARGET")" # Save name of target's basename (ex: 'input.txt' from '/tmp/input.txt').
+TARGET_DIRNAME="$(dirname "$TARGET")" # Save name of target's directory (ex: '/tmp' from '/tmp/input.txt').
+
+OUTPUT="$TARGET_DIRNAME"/"$TARGET_BASENAME".tar.xz # Define output file to be in same location as target but with .tar.xz extension.
+
+pushd "$TARGET_DIRNAME" 1>/dev/null 2>&1 # Temporarily navigate to directory holding TARGET.
+tar cf - "$TARGET_BASENAME" | xz -9e --lzma2=dict=1536MiB,mf=bt4,nice=273,depth=1000 > "$OUTPUT"
+echoerr "Archive saved at: $OUTPUT"
+popd 1>/dev/null 2>&1 # Return to original working directory.