A progress bar (gauge box)

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
← A menu boxHomeThe file selection box →
  • You can create a progress bar (progress indicator) when copying/moving files or making backups using the gauge box.
  • It displays a meter along the bottom of the box. The meter indicates the percentage. New percentages are read from standard input, one integer per line. The meter is updated to reflect each new percentage.
  • If the standard input reads the string "START_BAR", then the first line following is taken as an integer percentage, then subsequent lines up to another "START_BAR" are used for a new prompt. The gauge exits when EOF is reached on the standard input.
  • The syntax is as follows:
echo percentage | dialog --gauge "text" height width percent
echo "10" | dialog --gauge "Please wait" 10 70 0
echo "50" | dialog --gauge "Please wait" 10 70 0
echo "100" | dialog --gauge "Please wait" 10 70 0
  • However, you need to use the while or for loop to show 0 to 100% progress. In this example, the for loop is used to display progress:
for i in $(seq 0 10 100) ; do sleep 1; echo $i | dialog --gauge "Please wait" 10 70 0; done


Create a shell script dvdcopy.sh:

# dvdcopy.sh - A sample shell script to display a progress bar
# set counter to 0 
# set infinite while loop
while :
cat <<EOF
Disk copy /dev/dvd to /home/data ( $counter%):
# increase counter by 10
(( counter+=10 ))
[ $counter -eq 100 ] && break
# delay it a specified amount of time i.e 1 sec
sleep 1
) |
dialog --title "File Copy" --gauge "Please wait" 7 70 0

Save and close the file. Run it as follows:

chmod +x dvdcopy.sh

Sample outputs:

A sample progress bar (gauge box)

File Copy Progress Bar With Dialog

  • Create a shell script called pcp.sh:
# pcp.sh: A shell script to copy /bin/* and /etc/* files
#         Display a progress bar while copying files.  
# * Based upon Greg's (GreyCat's) GPLd wiki example. *
# --------------------------------------------------------
# Create an array of all files in /etc and /bin directory
DIRS=(/bin/* /etc/*)

# Destination directory

# Create $DEST if does not exits
[ ! -d $DEST ] && mkdir -p $DEST

# Show a progress bar
# ---------------------------------
# Redirect dialog commands input using substitution
dialog --title "Copy file" --gauge "Copying file..." 10 75 < <(
   # Get total number of files in array

   # set counter - it will increase every-time a file is copied to $DEST

   # Start the for loop 
   # read each file from $DIRS array 
   # $f has filename 
   for f in "${DIRS[@]}"
      # calculate progress
      PCT=$(( 100*(++i)/n ))

      # update dialog box 
cat <<EOF
Copying file "$f"...
  # copy file $f to $DEST 
  /bin/cp $f ${DEST} &>/dev/null

# just delete $DEST directory
/bin/rm -rf $DEST

Save and close the file. Run it as follows:

chmod +x pcp.sh
← A menu boxHomeThe file selection box →