0

I want to print a loop like below

a=0
while [ $a -lt 100 ]
do
   echo ${a}%
   a=`expr $a + 1`
   sleep 1
done

It throws output as follows

1%
2%
3%
4%
...

But I wanted to print like running value 1% replaced by 2%, etc. till 100% in the same line.

Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
logan
  • 7,946
  • 36
  • 114
  • 185

2 Answers2

2

You can use printf to print backspace character \b to remove the already printed characters as

printf "\b%.0s" {1..5}
  • This will print 5 backspaces where by the cursor will be moved to the start of the line.

    In the next iteration the the echo will produce the new number

Example

while [ $a -lt 100 ]
do    
    echo -n ${a}%;    
    a=`expr $a + 1`

    #This will remove the already printed value from the screen
    printf "\b%.0s" {1..5}
    sleep 1
done

OR

You can echo a carriage return as

echo -e "\r"

like

while [ $a -lt 100 ]
do    
    echo -n ${a}%;    
    a=`expr $a + 1`

    #This will remove the already printed value from the screen
    echo -e "\r"
    sleep 1
done
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0
function a(){
  if [[ $1 -le 100 ]]; then
    echo $1%
    b=`expr $1 + 1`
    sleep 1
    clear
    a $b
  fi
}
a 0

I think that this is you want... count 0 to 100 with recursivity in the same line