2 # Desc: Checks that a valid tar archive exists, creates one otherwise
4 #===BEGIN Declare local script functions===
5 yell
() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
6 die
() { yell
"$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
7 try
() { "$@" || die
"cannot $*"; } #o
9 # Desc: Checks that a valid tar archive exists, creates one otherwise
10 # Usage: checkMakeTar [ path ]
12 # Input: arg1: path of tar archive
13 # Output: exit code 0 : tar readable
14 # exit code 1 : tar missing; created
15 # exit code 2 : tar not readable; moved; replaced
16 # Depends: bash 5, date 8, tar 1, try()
17 local pathTar returnFlag0 returnFlag1 returnFlag2
20 # Check if file is a valid tar archive
21 if tar --list --file="$pathTar" 1>/dev
/null
2>&1; then
23 returnFlag0
="tar valid";
25 ## F1: Check if file exists
26 if [[ -f "$pathTar" ]]; then
28 try
mv "$pathTar" "$pathTar""--broken--""$(date +%Y%m%dT%H%M%S)" && \
29 returnFlag1
="tar moved";
34 ## F2: Create tar archive, return 0
35 try
tar --create --file="$pathTar" --files-from=/dev
/null
&& \
36 returnFlag2
="tar created";
39 # Determine function return code
40 if [[ "$returnFlag0" = "tar valid" ]]; then
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
47 } # checks if arg1 is tar; creates one otherwise
48 #===END Declare local script functions===
50 #====BEGIN sample code====
51 #myFile="/tmp/$(date +%s)..tar"
52 myFile
="/tmp/$(date +%Y%m%d).tar"
53 if [[ -f "$myFile" ]]; then yell
"$myFile already exists."; else yell
"$myFile doesn't yet exist."; fi
54 if checkMakeTar
"$myFile"; then
55 yell
"checkMakeTar() function run and exited:$?";
57 yell
"checkMakeTar() function run and exited:$?";
60 if [[ -f "$myFile" ]]; then
61 yell
"Now exists :$myFile";
64 yell
"Does not exist:$myFile";
67 #====END sample code====
69 # Author: Steven Baltakatei Sandoval