'How do you check the size of a tar archive before saving it without doing the compression twice?

I'm trying to make a bash script that will compress directory, and will check if there is space on the disk for the directory that needs to be compressed. The problem that I'm running into is that I can't find that out without first compressing the file and passing it to wc, and then if the condition passes, compress the file again, making the PC do the compression twice for no reason.

Current code:

EMPTY_SPACE=$(df -k . | awk 'NR==2 {print $4}')
ARCHIVE_SIZE=$(( $(tar czf - "$1" | wc -c )/1000 ))
if [ $EMPTY_SPACE -lt $ARCHIVE_SIZE ]; then
    echo "Not enough disk space to save the archive"
    exit 6
fi
tar czf ${1%/}".tar.gz" $1

What I would like to do is have some kind of conditional tee or the sort that would only fire if the [ $EMPTY_SPACE -lt $ARCHIVE_SIZE ] passes and would save the output of tar czf - "$1" to the disk.

One other idea for solving it was to save it temporarily in a variable, but saving a potentially multi GB file in a bash variable seems like just asking for trouble.

I've looked at the conditional pipeline post on the Unix StackExchange, but that only covers a conditional pipeline, and I can't (that I know of) use the same output of the tar czf - "$1" in 2 consecutive pipeline parts.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source