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