Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping dots until a process is complete? Bash

Tags:

linux

bash

I am trying to create a post-install bash script that I can use when I do fresh installs of Ubuntu. Thefirst feature I want is for the script to prompt the user whether they would like to update their system and if they select yes to display the word "loading" followed by a loop of dots until the process is finished and to export the output to a log file. I have managed to implement all these features except the loop with the dots.

#!/bin/bash

read -p "Update your system? [y/n]" RESP
if [ "$RESP" = "y" ] || [ "$RESP" = "Y" ] || [ "$RESP" = "Yes" ] || [ $RESP = "yes" ]; then
    echo "Loading..." #dot loop to show that process is occurring    
    sudo apt-get update>>log.txt 2>&1 #when complete want the dots to stop looping.
    echo $?>>log.txt 2>&1  
    echo "UPDATE COMPLETE">>log.txt 2>&1
    echo "----------------------------------------------------------------------------------------------------------------------------------------------------">>log.txt 2>&1
    echo "----------------------------------------------------------------------------------------------------------------------------------------------------">>log.txt 2>&1
    echo "Status=$?"    
    echo "Done"
    sleep 2
    clear
else
    echo "OK"
fi
like image 745
user2674660 Avatar asked Sep 18 '14 03:09

user2674660


Video Answer


1 Answers

#!/bin/bash

"$@" &

while kill -0 $!; do
    printf '.' > /dev/tty
    sleep 2
done

printf '\n' > /dev/tty

Save this as a script named run_with_dots. Then you can do:

sudo ./run_with_dots apt-get update >>log.txt 2>&1

You can pass any command and it'll run it and print dots every two seconds until the command finishes. "$@" & treats the script's arguments as the command to run, with & doing it in the background. It uses kill -0 to check if the process is still running ($! is the PID of the backgrounded process). The dots are printed to /dev/tty since your want to redirect both stdout and stderr.

like image 117
John Kugelman Avatar answered Sep 18 '22 23:09

John Kugelman