3 # Desc: Checks that a valid tar archive exists, creates one otherwise
5 #===BEGIN Declare local script functions===
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 # Desc: Checks that a valid tar archive exists, creates one otherwise
11 # Usage: checkMakeTar [ path ]
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
21 # Check if file is a valid tar archive
22 if tar --list --file="$PATH_TAR" 1>/dev
/null
2>&1; then
24 returnFlag0
="tar valid";
26 ## F1: Check if file exists
27 if [[ -f "$PATH_TAR" ]]; then
29 try
mv "$PATH_TAR" "$PATH_TAR""--broken--""$(date +%Y%m%dT%H%M%S)" && \
30 returnFlag1
="tar moved";
35 ## F2: Create tar archive, return 0
36 try
tar --create --file="$PATH_TAR" --files-from=/dev
/null
&& \
37 returnFlag2
="tar created";
40 # Determine function return code
41 if [[ "$returnFlag0" = "tar valid" ]]; then
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
48 } # checks if arg1 is tar; creates one otherwise
49 #===END Declare local script functions===
51 #====BEGIN sample code====
52 #myFile="/tmp/$(date +%s)..tar"
53 myFile
="/tmp/$(date +%Y%m%d).tar"
54 if [[ -f "$myFile" ]]; then yell
"$myFile already exists."; else yell
"$myFile doesn't yet exist."; fi
55 if checkMakeTar
"$myFile"; then
56 yell
"checkMakeTar() function run and exited:$?";
58 yell
"checkMakeTar() function run and exited:$?";
61 if [[ -f "$myFile" ]]; then
62 yell
"Now exists :$myFile";
65 yell
"Does not exist:$myFile";
68 #====END sample code====
70 # Author: Steven Baltakatei Sandoval