style(unitproc):appendFileTar():VAR_NAME to varName
[BK-2020-03.git] / unitproc / bktemp-checkMakeTar
CommitLineData
949d90f8 1#!/bin/bash
949d90f8
SBS
2# Desc: Checks that a valid tar archive exists, creates one otherwise
3
785dbf38 4#===BEGIN Declare local script functions===
949d90f8
SBS
5yell() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
6die() { yell "$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
7try() { "$@" || die "cannot $*"; } #o
949d90f8
SBS
8checkMakeTar() {
9 # Desc: Checks that a valid tar archive exists, creates one otherwise
10 # Usage: checkMakeTar [ path ]
9c7ec3f7 11 # Version: 1.0.2
949d90f8 12 # Input: arg1: path of tar archive
b13c9582
SBS
13 # Output: exit code 0 : tar readable
14 # exit code 1 : tar missing; created
15 # exit code 2 : tar not readable; moved; replaced
9c7ec3f7
SBS
16 # Depends: bash 5, date 8, tar 1, try()
17 local pathTar returnFlag0 returnFlag1 returnFlag2
18 pathTar="$1";
949d90f8
SBS
19
20 # Check if file is a valid tar archive
9c7ec3f7 21 if tar --list --file="$pathTar" 1>/dev/null 2>&1; then
949d90f8 22 ## T1: return success
b13c9582 23 returnFlag0="tar valid";
949d90f8
SBS
24 else
25 ## F1: Check if file exists
9c7ec3f7 26 if [[ -f "$pathTar" ]]; then
949d90f8 27 ### T: Rename file
9c7ec3f7 28 try mv "$pathTar" "$pathTar""--broken--""$(date +%Y%m%dT%H%M%S)" && \
b13c9582 29 returnFlag1="tar moved";
949d90f8
SBS
30 else
31 ### F: -
32 :
9c7ec3f7 33 fi;
949d90f8 34 ## F2: Create tar archive, return 0
9c7ec3f7 35 try tar --create --file="$pathTar" --files-from=/dev/null && \
b13c9582 36 returnFlag2="tar created";
9c7ec3f7 37 fi;
b13c9582
SBS
38
39 # Determine function return code
40 if [[ "$returnFlag0" = "tar valid" ]]; then
949d90f8 41 return 0;
b13c9582
SBS
42 elif [[ "$returnFlag2" = "tar created" ]] && ! [[ "$returnFlag1" = "tar moved" ]]; then
43 return 1; # tar missing so created
44 elif [[ "$returnFlag2" = "tar created" ]] && [[ "$returnFlag1" = "tar moved" ]]; then
45 return 2; # tar not readable so moved; replaced
9c7ec3f7 46 fi;
949d90f8
SBS
47} # checks if arg1 is tar; creates one otherwise
48#===END Declare local script functions===
49
50#====BEGIN sample code====
b13c9582
SBS
51#myFile="/tmp/$(date +%s)..tar"
52myFile="/tmp/$(date +%Y%m%d).tar"
53if [[ -f "$myFile" ]]; then yell "$myFile already exists."; else yell "$myFile doesn't yet exist."; fi
949d90f8
SBS
54if checkMakeTar "$myFile"; then
55 yell "checkMakeTar() function run and exited:$?";
56else
57 yell "checkMakeTar() function run and exited:$?";
58fi
59
60if [[ -f "$myFile" ]]; then
61 yell "Now exists :$myFile";
62 ls -l "$myFile";
63else
64 yell "Does not exist:$myFile";
65 ls -l "$myFile";
66fi
67#====END sample code====
0cef41dd
SBS
68
69# Author: Steven Baltakatei Sandoval
70# License: GPLv3+