【问题标题】:Spinner Animation and echo command微调器动画和回显命令
【发布时间】:2018-04-24 09:37:18
【问题描述】:

这是我的 bash 文件的一部分。我需要的输出是:

[ - ] KatworX© Tech. 版权所有。由 Arjun Singh Kathait 开发并由 ☆Stack Overflow 社区调试☆

我希望微调器动画在显示回显命令时继续旋转 5 秒。社区可以帮忙吗???

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 "\b\b\b\b\b\b"
        done
    }

         sleep 5 & spinner | echo -e "\nCopyright of KatworX© Tech. Developed by Arjun Singh Kathait and Debugged by the ☆Stack Overflow Community☆"

【问题讨论】:

  • 看看multiple colors on output of bash spinner。您可以忽略颜色的变化。但是在 while 循环中调用 psawkgrep 效率非常低。
  • 可以修改这段代码段@DavidC.Rankin 并发布到评论区吗?

标签: bash shell unix terminal gnome-terminal


【解决方案1】:

从评论继续。为了避免在每次迭代中调用psawkgrep,您需要将PID 作为参数传递给spin 函数。 (并且您可以传递一个字符串来显示并默认为您的字符串)。我会做类似的事情:

#!/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 "\033[1;34m"
    while [ -d /proc/$PROC ]; do
        printf '\033[s\033[u[ / ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ — ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ \ ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ | ] %s\033[u' "$str"; sleep "$delay"
    done
    printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "  # return to normal
    tput cnorm  # restore cursor
    return 0
}

## simple example with sleep
sleep 5 &

spinner $!

(它显示为蓝色 -- 但您可以删除第一个 printf 以去除颜色)

【讨论】:

  • 非常感谢@David。是像你这样的人让这个社区变得更美好。我已将我当前的项目专门用于 Stack Overflow 社区,因为它在调试等方面有很大帮助。
  • 当然,很高兴为您提供帮助。你甚至可以添加一个local delay="${3:-0.1}" 并将延迟作为一个选项传递,如果你想让它也可以调整的话。祝你的脚本好运。
  • 您可以将while [ -d /proc/$PROC ]; do 替换为while kill -0 ${PROC} 2>/dev/null; do 以使其跨平台
  • 如果不是Linux平台,那么请密切注意man kill语法。 kill -0 ${PROC} 2>/dev/null 应该可以工作——只要-0 信号什么都不发送,但会像在 Linux 上一样报告错误。你在哪里有 kill 但没有 procfs?
  • @DavidC.Rankin 通常在“Unixes”中,FreeBSD 有一个不错的pwait,但在 macOS 中,kill -0 $pid 可以解决问题
猜你喜欢
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2015-06-28
  • 2018-09-29
相关资源
最近更新 更多