style(user/bkytpldl-generic):Adjust comment
[BK-2020-03.git] / user / bkxz
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
13 echoerr() { echo "$@" 1>&2; } # Define error display function.
14
15 TARGET="$1" # Identify first argument as target file or directory.
16
17 if ! command -v tar >/dev/null 2>&1; then # Check that 'tar' command exists.
18 echoerr "ERROR: Command doesn't exist: tar";
19 fi
20
21 if ! 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;
24 fi
25
26 if ! ( [ -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;
28 fi
29
30
31 TARGET_BASENAME="$(basename "$TARGET")" # Save name of target's basename (ex: 'input.txt' from '/tmp/input.txt').
32 TARGET_DIRNAME="$(dirname "$TARGET")" # Save name of target's directory (ex: '/tmp' from '/tmp/input.txt').
33
34 OUTPUT="$TARGET_DIRNAME"/"$TARGET_BASENAME".tar.xz # Define output file to be in same location as target but with .tar.xz extension.
35
36 pushd "$TARGET_DIRNAME" 1>/dev/null 2>&1 # Temporarily navigate to directory holding TARGET.
37 tar cf - "$TARGET_BASENAME" | xz -9e --lzma2=dict=1536MiB,mf=bt4,nice=273,depth=1000 > "$OUTPUT"
38 echoerr "Archive saved at: $OUTPUT"
39 popd 1>/dev/null 2>&1 # Return to original working directory.