Search code examples
bashsh

Shell Script Spinner Shows the PID


I'm trying to fake show a spinner when I "need" to run a long running piece of code (ok, so, it isn't long running, but I want it to seem that it is to my end user...)

On Android 12+

So, I've got the following shell script:

#!/system/bin/sh

# the spinner function
spinner() { 
    # show the spinner
    (
        while :; do 
            for c in / - \\ \|; do 
                printf '%s\b' "$c"; 
                sleep 0.025; 
            done; 
        done
    )& 
    
    # sleep the length of time specified when calling this
    sleep $(($1-1)); 
    
    # backspace and kill the process
    { 
        printf '\b'; 
        kill $! && wait $!; 
    } 2>/dev/null 
}

# call it!
spinner 5

It shows my spinner for 5 seconds, but also displays the following: [1] 17823 before it... (which appears to be the pid of this, so that last number always changes...)

Any ideas how I can get rid if that?


Solution

  • With a couple of changes, this worked for me :

    #!/bin/sh
    
    # the spinner function
    spinner() { 
        # show the spinner
        {
            while :; do
                for c in / - \\ \|; do
                    printf '%s\b' "$c";
                    sleep 0.025; 
                done; 
            done &
        } 2>/dev/null
        
        # sleep the length of time specified when calling this
        sleep $(($1-1));
        
        # backspace and kill the process
        { 
            printf '\b'; 
            kill $! && wait $!; 
        } 2>/dev/null
    }
    
    # call it!
    spinner 5