In this lesson, you will learn how to provide visual feedback for long-running scripts by implementing an interactive progress bar using standard Bash features.
When you run a script that performs a time-consuming task—like a heavy file migration or a lengthy data download—a terminal that simply sits there can feel like it has crashed. To improve the user experience, we can use an interactive progress bar to signal that work is actively progressing.
The Logic of the Progress Bar
At its core, a progress bar in the terminal is simply a line of text that you update repeatedly in the same position. To achieve this, we use the carriage return character \r. Unlike the newline character (\n), which moves the cursor down to the next row, \r moves the cursor back to the start of the current row. This allows us to overwrite the previous output with an updated status.
A Practical Implementation
Here is how you can implement a simple progress indicator in your scripts:
#!/bin/bash
# Total number of tasks
total=10
for ((i=1; i<=total; i++)); do
# Perform the task (simulated by sleep)
sleep 0.5
# Calculate percentage
percent=$((i * 100 / total))
# Print the progress bar
# -ne prevents a newline, \r returns to start
printf "\rProgress: [%-10s] %d%%" "#" "$percent"
done
echo -e "\nTask complete!"
In this snippet, the printf command acts as our primary tool. The %-10s format specifier creates a fixed-width space for our bar, and \r ensures that every time the loop iterates, the new state of the progress bar visually replaces the old one. By combining this with logic from your previous experience in Interactive Prompt UI Design, you ensure that your scripts feel polished and responsive rather than stagnant.
When building these, remember to keep the calculations simple. You want the visual update to be a lightweight addition to your logic, not a source of performance overhead.
Key Takeaway: Use the carriage return character \r to overwrite the current line in your terminal, creating the illusion of a smooth, updating progress bar.