Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - Spinner Animation and echo command

This is a part of my bash file. The output I need is:

[ - ] Copyright of KatworX? Tech. Developed by Arjun Singh Kathait and Debugged by the ☆Stack Overflow Community☆

I want the spinner animation to continue spinning for 5 seconds while the echo command is being displayed. Can the community help???

spinner()
    {
        local pid=$!
        local delay=0.75
        local spinstr='|/-'
        while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
            local temp=${spinstr#?}
            printf " [%c]  " "$spinstr"
            local spinstr=$temp${spinstr%"$temp"}
            sleep $delay
            printf ""
        done
    }

         sleep 5 & spinner | echo -e "
Copyright of KatworX? Tech. Developed by Arjun Singh Kathait and Debugged by the ☆Stack Overflow Community☆"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Continuing from the comment. To avoid calling ps, awk and grep on every iteration, you need to pass the PID as an argument to the spin function. (and you can pass a string to display and default to your string as well). I would do something similar to:

#!/bin/bash

## spinner takes the pid of the process as the first argument and
#  string to display as second argument (default provided) and spins
#  until the process completes.
spinner() {
    local PROC="$1"
    local str="${2:-'Copyright of KatworX? Tech. Developed by Arjun Singh Kathait and Debugged by the ☆Stack Overflow Community☆'}"
    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
    printf '33[s33[u%*s33[u33[0m' $((${#str}+6)) " "  # return to normal
    tput cnorm  # restore cursor
    return 0
}

## simple example with sleep
sleep 5 &

spinner $!

(it displays in blue -- but you can delete the first printf to remove the color)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...