I’m working on a Bash script where I need to show a spinner animation function while checking if a specified Git remote exists. The script snippet for checking the Git remote is as follows:
read remote_to_pull_from
if ! git remote show $remote_to_pull_from &>/dev/null; then
echo "Remote '$remote_to_pull_from' does not exist, exiting..."
return 1
fi
This snippet works correctly and checks if the remote exists. Now, I want to add a spinner function to show an animation while the git remote show command is running. The spinner function, credited to this post, is as follows:
spinner() {
local PROC="$1"
local str="${2:-'Running...'}"
local delay="0.1"
tput civis # hide cursor
printf "33[1;34m"
while [ -d /proc/$PROC ]; do
printf '33[s33[u[ / ] %s33[u' "$str"; sleep "$delay"
printf '33[s33[u[ — ] %s33[u' "$str"; sleep "$delay"
printf '33[s33[u[ ] %s33[u' "$str"; sleep "$delay"
printf '33[s33[u[ | ] %s33[u' "$str"; sleep "$delay"
done
tput cnorm # restore cursor
return 0
}
I attempted to integrate the spinner with my conditional check using the approach mentioned in the Stack Overflow post, where the spinner animation is run in the background using a background operator (&). Here is the code I used to get it running while my conditions is being checked:
```read remote_to_pull_from
if ! git remote show $remote_to_pull_from &>/dev/null & spinner $!; then
echo "Remote '$remote_to_pull_from' does not exist, exiting..."
return 1
fi```
The spinner spins, but the condition fails, and the script prints "Remote '$remote_to_pull_from' does not exist, exiting...". Without the spinner, the condition works correctly.
I'm expecting the spinner function to run while the git remote show command is executing, and if the remote doesn't exist, the script should echo the error message and exit. How can I correctly use this spinner function with my conditional check, I think I'm missing a logical step here and breaking the condition when mixing it with that function? How can I handle this? Additionally, can you explain the usage of $! in this context?
Thank you everyone.
New contributor
Ilgar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.