Home > OS >  Need a shell script for spinning cursor
Need a shell script for spinning cursor

Time:03-02

I need a shell script for spinning cursor which I can use with "copying" function. I tried below program and it works but the only problem I have here is that the spinner is showing below the text.

#!/bin/bash
spinner=('\' '/' '-' '\')

copy(){
echo "copying files..."
spin &
pid=$!
for i in `seq 1 10`
do 
sleep 1
done
kill $pid
echo ""
}

spin(){
while [ 1 ]
do 
for i in "${spinner[@]}"
do
echo -ne "\r$i"
sleep 0.2
done
done
}
copy

Expected Output: Copying files...\

CodePudding user response:

Print the text Copying files... without trailing newline, if you don't want one:

echo -n Copying files...

CodePudding user response:

#!/bin/bash

spinner () {
    local chars=('|' / - '\')

    # hide the cursor
    tput civis
    trap 'printf "\010"; tput cvvis; return' INT TERM

    printf %s "$*"

    while :; do
        for i in {0..3}; do
            printf %s "${chars[i]}"
            sleep 0.3
            printf '\010'
        done
    done
}

copy ()
{
    local pid return

    spinner 'Copying 5 files... ' & pid=$!

    # Slow copy command here
    sleep 4

    return=$?

   # kill spinner, and wait for the trap commands to complete
    kill "$pid"
    wait "$pid"

    if [[ "$return" -eq 0 ]]; then
        echo done
    else
        echo ERROR
    fi
}

copy

Depending on how you use this, you probably want to hide the cursor earlier, and show it later. Instead of turning it on and off for multiple copy or spinner invocations. Eg:

#!/bin/bash

trap 'tput cvvis' EXIT
tput civis

copy
copy
# other stuff

The cursor is hidden when tput civis runs, and un-hidden (tput cvvis) when the script exits (normally, or due to interrupt etc). If you do it like this, remove the corresponding tput commands from the function (but keep the other trap commands).

The reason for hiding the cursor is that it can mess with the spinner animation.

  • Related