Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Shell, display something while a command is running in the background

Tags:

linux

bash

shell

I want to make a short script, just for experiment purposes. For example, I run a command such as

sudo apt-get install eclipse --yes

and instead of displaying the verbose of the command while its installing it, display a loading bar like ...... (dots just popping up while it loads or something)

I tried doing something like

apt=sudo apt-get install vlc --yes

start()
{
    $apt
    while $apt;
    do
        echo -n "."
        sleep 0.5
    done
}
start

(what I intended to do was to run the $apt variable and then make it move on to the while loop and the while loop will determine if the command is running, so while the command is running it will replace the verbose with dots)

like image 838
xR34P3Rx Avatar asked Dec 15 '22 09:12

xR34P3Rx


2 Answers

apt-get install vlc --yes >/tmp/apt-get.log & # Run in background, with output redirected
pid=$! # Get PID of background command
while kill -0 $pid  # Signal 0 just tests whether the process exists
do
  echo -n "."
  sleep 0.5
done

Put the above in a script and run it via sudo. You can't use kill to test the sudo process itself, because you can't send signals to a process with a different uid.

like image 161
Barmar Avatar answered Jan 19 '23 00:01

Barmar


Here's a small variation on the ones above...

spinner()
{
    local pid=$!
    local delay=0.75
    local spinstr='...'
    echo "Loading "
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf "%s  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b"
    done
    printf "    \b\b\b\b"
}

with usage:

(a_long_running_task) &
spinner

This prints out

Loading ...

Loading ....

Loading .....

Loading ......

On the same line of course.

like image 38
wizurd Avatar answered Jan 18 '23 23:01

wizurd