需要一个 shell 脚本来旋转光标

Need a shell script for spinning cursor

我需要一个 shell 脚本来旋转光标,我可以将其与“复制”功能一起使用。我尝试了下面的程序并且它有效但我在这里遇到的唯一问题是微调器显示在文本下方。

#!/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

预期输出: 正在复制文件...\

打印文本 正在复制文件... 不带尾随换行符,如果您不想要的话:

echo -n Copying files...
#!/bin/bash

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

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

    printf %s "$*"

    while :; do
        for i in {0..3}; do
            printf %s "${chars[i]}"
            sleep 0.3
            printf '0'
        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

根据您的使用方式,您可能希望先隐藏光标,然后再显示。而不是为多个 copyspinner 调用打开和关闭它。例如:

#!/bin/bash

trap 'tput cvvis' EXIT
tput civis

copy
copy
# other stuff

光标在 tput civis 运行时隐藏,un-hidden (tput cvvis) 在脚本退出时(通常,或由于中断等)。如果你这样做,从函数中删除相应的 tput 命令(但保留其他陷阱命令)。

隐藏光标的原因是它会扰乱微调器动画。