Created
January 27, 2016 17:42
-
-
Save jlinoff/63a180d85a9e8041915c to your computer and use it in GitHub Desktop.
Bash example to report the progress of dealing with n items that also has an estimate of time remaining.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Function to measure and report progress. | |
# A bit like PV but for general things like copying N files. | |
# Use it as a starting point to created your own. | |
# | |
# License: MIT Open Source | |
# Copyright (c) 2016 Joe Linoff | |
# Show the progress of N items with an estimate of the time remaining. | |
# Start The start time (date +'%s'). | |
# TotalItems The total number of items. | |
# CurrItem The index of the current item. The "last" CurrItem must | |
# match TotalItems for this function to be accurate. | |
function progress() { | |
local Start=$1 | |
local TotalItems=$2 | |
local CurrItem=$3 | |
if (( TotalItems > 0 && CurrItem > 0 )) ; then | |
local Per=$(echo "scale=4 ; ($CurrItem * 100) / $TotalItems" | bc) | |
local Now=$(date +'%s') | |
local Elapsed=0 | |
((ElapsedTime=Now - Start)) | |
local TotalTime=$(echo "scale=4 ; $ElapsedTime * ($TotalItems / $CurrItem)" | bc) | |
local RemainingTime=$(echo "scale=4 ; $TotalTime - $ElapsedTime" | bc) | |
# Fields reported: | |
# $CurrItem The n-th item. The $CurrItem must match $TotalItems (e.g. 1 based). | |
# $TotalItems The total number of items. | |
# $Per The percentage completed. | |
# $ElapsedTime The number of seconds that have elapsed since starting. | |
# $TotalTime An estimate of the total time required to finish. | |
# $RemainingTime An estimate of the time remaining. | |
printf '\r\033[K%6d %6d %5.1f%% %d %.1f %.1f ' $CurrItem $TotalItems $Per $ElapsedTime $TotalTime $RemainingTime | |
fi | |
} | |
# Example: Show the progress of dealing with NumItems. | |
NumItems=1000 | |
Start=$(date +'%s') | |
for((i=1; i<=NumItems; i++)) ; do | |
progress $Start $NumItems $i | |
sleep 0.02 | |
done | |
printf '\n' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment