@stacksofplates said in Return Values in Bash Script and generate e-mail which shows successes, errors and if the directory is empty:
Rather than mess with multiple arrays, you can just have a single dictionary that holds the file and status. A single function can decrypt the file. Then just save the file name and status of the decryption in that dictionary. Then loop through the dictionary and here I just print the data, but you could email it or send to Slack or whatever.
This was a quick pass so probably can be cleaned up a bit.
My reasoning behind two arrays was to keep it organized. If I do all successes in one and then all failures in the other. So I have this now:
#!/usr/bin/env bash
source "/home/user1/subdirectory1/master.sh"
decryptedFolderPath="/home/user2/subdirectory2/"
archiveFolderPath="/home/user1/subdirectory1/archive/in/"
extension=${fileName##*\.}
newFileName=${fileName%.*}
fileWithoutTimestamp="$newFileName.$extension"
encryptedItems=$(ls encryptedFolderPath*.pgp)
statusArray=()
for i in $encryptedItems
do
gpg --batch --homedir /home/user1/.gnupg/ --passphrase "$PASS" --list-only --list-packets --yes --decrypt "$i" | grep -q "encrypted" > "$decryptedFolderPath"/"$fileWithoutTimestamp"
outPut=$(gpg --batch --homedir /home/user1/.gnupg/ --passphrase "$PASS" --list-only --list-packets --yes "$i" | grep -q "encrypted")
if [ $? != 0 ]; then
echo "$i is not a pgp file"
statusArray+=("failed to decrypt $i, with status code $? output from pgp: $outPut")
fi
if [ $? == 0 ]; then
statusArray+=("Succesfully Decrypted $i")
echo ${#statusArray[@]} | mail -s 'report' [email protected]
v=${i%.*}
encryptedFile="$v"
fileName=${encryptedFile##*/}
@@ -27,4 +34,4 @@ continue
fi
done
mv "$i" "$archiveFolderPath"
I think this is what you meant, right?