Integrate Progress Indicator in Console Output

I recently tried to use pv in a bash script so that it wouldn’t interfere with my concept of communicating overall progress to the user.

When I usually like to do is to echo -n a description of the current task and then later echo either “Done.” or “Failed!” (or something similar).
Obviously, that somewhat conflicts with pv. So here is the solution:

# Create backup archive
_statusMessage="Compressing installation..."
echo -n $_statusMessage
if hash pv 2>&- && hash gzip 2>&- && hash du 2>&-; then
  echo
  _folderSize=`du --summarize --bytes $BASE | cut --fields 1`
  if ! tar --create --file - $BASE | pv --progress --rate --bytes --size $_folderSize | gzip --best > $FILE; then
    echo "Failed!"
    exit 1
  fi
  # Clear pv output and position cursor after status message
  tput cuu 2 && tput cuf ${#_statusMessage} && tput ed
else
  if ! tar --create --gzip --file $FILE $BASE; then
    echo "Failed!"
    exit 1
  fi
fi

echo "Done."

The snippet also shows how to conditionally use pv if it is available, which I really like.

Leave a Reply

You must be logged in to post a comment.