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