BASH
Create a Command-Line Progress Spinner in Bash
Enhance the user experience of long-running Bash scripts by implementing an animated progress spinner directly in the terminal, providing visual feedback during operations.
#!/bin/bash
SPINNER_PID=""
# Function to display a spinning cursor
function start_spinner {
local pid=$!
local delay=0.1
local spin_chars=("-" "\" " "|" "/")
trap "stop_spinner" SIGINT # Catch Ctrl+C to stop spinner cleanly
while kill -0 "$pid" 2>/dev/null; do
for char in "${spin_chars[@]}"; do
printf "\r%s %s" "Processing..." "$char"
sleep "$delay"
done
done
printf "\r%s
" "Processing... Done!"
}
# Function to stop the spinner and clean up
function stop_spinner {
if [ -n "$SPINNER_PID" ]; then
kill "$SPINNER_PID" 2>/dev/null
wait "$SPINNER_PID" 2>/dev/null # Wait for the spinner to actually exit
fi
printf "\r%s
" "Operation interrupted!" # Or just clear line
exit 1
}
# Main script logic
# --- Example: Simulate a long-running task ---
(sleep 7; echo "Task finished in background.") &
TASK_PID=$!
# Start the spinner in the background, passing the task's PID to it
start_spinner "$TASK_PID" &
SPINNER_PID=$!
# Wait for the actual task to complete
wait "$TASK_PID"
# Stop the spinner (if it's still running for some reason, though `start_spinner` should self-terminate)
if kill -0 "$SPINNER_PID" 2>/dev/null; then
kill "$SPINNER_PID"
wait "$SPINNER_PID" 2>/dev/null
fi
echo "
Script execution completed successfully."
How it works: This script provides a simple animated progress spinner for Bash. The `start_spinner` function runs in the background, continuously printing and overwriting a character sequence (`- \ | /`) to the terminal using `printf "\r"`. It monitors a target `pid` (the PID of the long-running task) and stops when that process finishes. A `trap` is included to handle `Ctrl+C` gracefully, ensuring the spinner is removed before the script exits. This improves the user experience for scripts that perform operations requiring some time.