Merge branch 'master' of https://zdv2.bktei.com/gitweb/baltakatei-exdev
[BK-2020-03.git] / user / bkxz
CommitLineData
2feb5df8
SBS
1#!/bin/bash
2
3# Date: 2020-04-09T00:09Z
4
5# Author: Steven Baltakatei Sandoval
6
7# Description: Compresses a file or directory using xz at max
8# settings. Saves compressed .tar.xz file in the same directory as the
9# original file.
10
11# Usage: bkxz [ file or dir ]
12
13echoerr() { echo "$@" 1>&2; } # Define error display function.
14
15TARGET="$1" # Identify first argument as target file or directory.
16
17if ! command -v tar >/dev/null 2>&1; then # Check that 'tar' command exists.
18 echoerr "ERROR: Command doesn't exist: tar";
19fi
20
21if ! command -v xz >/dev/null 2>&1; then # check that 'xz' command exist.
22 echoerr "ERROR: Command doesn't exist: xz. Suggestion: Install 'xz-utils' package.";
23 exit 1;
24fi
25
26if ! ( [ -f "$TARGET" ] || [ -d "$TARGET" ] ); then # check that TARGET is a file or dir.
27 echoerr "ERROR: Target is not a file or dir."; exit 1;
28fi
29
30
31TARGET_BASENAME="$(basename "$TARGET")" # Save name of target's basename (ex: 'input.txt' from '/tmp/input.txt').
32TARGET_DIRNAME="$(dirname "$TARGET")" # Save name of target's directory (ex: '/tmp' from '/tmp/input.txt').
33
34OUTPUT="$TARGET_DIRNAME"/"$TARGET_BASENAME".tar.xz # Define output file to be in same location as target but with .tar.xz extension.
35
36pushd "$TARGET_DIRNAME" 1>/dev/null 2>&1 # Temporarily navigate to directory holding TARGET.
37tar cf - "$TARGET_BASENAME" | xz -9e --lzma2=dict=1536MiB,mf=bt4,nice=273,depth=1000 > "$OUTPUT"
38echoerr "Archive saved at: $OUTPUT"
39popd 1>/dev/null 2>&1 # Return to original working directory.