Slash animation in bash

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
Fexonchik

Slash animation in bash

Post by Fexonchik »

Hi! I have one question, how to make a slash animation in bash? That is, there was a position \, then -,/, - and so on. Thank you in advance!
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 2 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
xenopeek
Level 25
Level 25
Posts: 29459
Joined: Wed Jul 06, 2011 3:58 am

Re: Slash animation in bash

Post by xenopeek »

I have this function in one of my scripts to show a spinner. You call the it with a bash statement as argument. When the bash statement returns false it stops the spinner. So it shows an animated spinner while waiting for some condition. If stdout isn't connected to a terminal it correctly doesn't output anything.

Code: Select all

spinner() {
  local condition="$1"
  if [[ -t 1 ]]; then
    local frame=1
    local frames='-\|/'
    echo -n ' '
    until eval "$condition"; do
      echo -n $'\b'"${frames:frame++%${#frames}:1}"
      sleep .1
    done
    echo -n $'\b'
  else
    while eval "$condition"; do
      sleep .1
    done
  fi
}
For example given $pid is the PID of a process started in the background, the following code would show the animated spinner until the background process has exited:

Code: Select all

spinner "! kill -0 $pid &>/dev/null"
Image
User avatar
Termy
Level 12
Level 12
Posts: 4254
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: Slash animation in bash

Post by Termy »

My AutoExec program has such a spinner, too. It starts at line 224, but there's a bit more going on; you should be able to get an idea as to how it works though.
xenopeek wrote: Sun Dec 27, 2020 11:50 am ...
Awesome spinner usage! Very cool stuff.
I'm also Terminalforlife on GitHub.
Locked

Return to “Scripts & Bash”