0
0
Bash Scriptingscripting~5 mins

Progress indicators in Bash Scripting

Choose your learning style9 modes available
Introduction
Progress indicators show users that a task is running and how much is done. They make waiting less boring and give feedback.
When copying large files and you want to show how much is copied.
When running a script that takes time, like downloading or installing software.
When processing many items in a loop and you want to show progress.
When waiting for a background task to finish and you want to keep the user informed.
Syntax
Bash Scripting
# Simple spinner example
while :; do
  for c in '-' '\\' '|' '/'; do
    printf '\r%c' "$c"
    sleep 0.1
  done
 done
Use \r to return the cursor to the start of the line to overwrite the previous character.
Sleep controls how fast the spinner moves.
Examples
Shows a spinner with the text 'Processing...' updating every 0.2 seconds.
Bash Scripting
# Spinner showing progress
while :; do
  for c in '-' '\\' '|' '/'; do
    printf '\rProcessing... %c' "$c"
    sleep 0.2
  done
 done
Shows a progress bar filling up from 0% to 100% in steps of 5%.
Bash Scripting
# Progress bar example
for i in {1..20}; do
  sleep 0.1
  printf '\r['
  for ((j=0; j<i; j++)); do printf '='; done
  for ((j=i; j<20; j++)); do printf ' '; done
  printf '] %d%%' $((i * 5))
done
printf '\n'
Sample Program
This script shows a spinner next to 'Working...' for 2 seconds, then prints 'Done!'.
Bash Scripting
#!/bin/bash
# Simple spinner while sleeping
spin='-|/\\'
printf 'Working... '
for i in {1..20}; do
  printf '\rWorking... %c' "${spin:i%4:1}"
  sleep 0.1
done
printf '\nDone!\n'
OutputSuccess
Important Notes
Use \r (carriage return) to overwrite the same line instead of printing new lines.
Make sure to flush output if needed (printf usually does this).
Keep the spinner or progress bar simple to avoid flickering.
Summary
Progress indicators give feedback during long tasks.
Use \r to update the same line in the terminal.
Spinners and progress bars are common types of indicators.