3 # Desc: Checks that a valid tar archive exists, creates one otherwise
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
10 #===BEGIN Declare local script functions===
12 # Desc: Checks that a valid tar archive exists, creates one otherwise
13 # Usage: checkMakeTar [ path ]
15 # Input: arg1: path of tar archive
16 # Output: exit code 0 : tar readable
17 # exit code 1 : tar missing; created
18 # exit code 2 : tar not readable; moved; replaced
19 # Depends: try, tar, date
20 local PATH_TAR returnFlag0 returnFlag1 returnFlag2
23 # Check if file is a valid tar archive
24 if tar --list --file="$PATH_TAR" 1>/dev
/null
2>&1; then
26 returnFlag0
="tar valid";
28 ## F1: Check if file exists
29 if [[ -f "$PATH_TAR" ]]; then
31 try
mv "$PATH_TAR" "$PATH_TAR""--broken--""$(date +%Y%m%dT%H%M%S)" && \
32 returnFlag1
="tar moved";
37 ## F2: Create tar archive, return 0
38 try
tar --create --file="$PATH_TAR" --files-from=/dev
/null
&& \
39 returnFlag2
="tar created";
42 # Determine function return code
43 if [[ "$returnFlag0" = "tar valid" ]]; then
45 elif [[ "$returnFlag2" = "tar created" ]] && ! [[ "$returnFlag1" = "tar moved" ]]; then
46 return 1; # tar missing so created
47 elif [[ "$returnFlag2" = "tar created" ]] && [[ "$returnFlag1" = "tar moved" ]]; then
48 return 2; # tar not readable so moved; replaced
50 } # checks if arg1 is tar; creates one otherwise
51 #===END Declare local script functions===
53 #====BEGIN sample code====
54 #myFile="/tmp/$(date +%s)..tar"
55 myFile
="/tmp/$(date +%Y%m%d).tar"
56 if [[ -f "$myFile" ]]; then yell
"$myFile already exists."; else yell
"$myFile doesn't yet exist."; fi
57 if checkMakeTar
"$myFile"; then
58 yell
"checkMakeTar() function run and exited:$?";
60 yell
"checkMakeTar() function run and exited:$?";
63 if [[ -f "$myFile" ]]; then
64 yell
"Now exists :$myFile";
67 yell
"Does not exist:$myFile";
70 #====END sample code====
72 # Author: Steven Baltakatei Sandoval