Search code examples
bashshellwgetcutwhiptail

bash - getting a number from a stream


The typical output recorded into chk file from the command:

wget -O - http://website/file > /dev/null 2>chk &

is something like :

   0K .......... .......... .......... .......... ..........  0%  143K 62s

  50K .......... .......... .......... .......... ..........  1%  433K 41s

 100K .......... .......... .......... .......... ..........  1% 1.20M 30s

 150K .......... .......... .......... .......... ..........  2%  259K 31s

 200K .......... .......... .......... .......... ..........  2% 83.2M 24s

...

 8800K .......... .......... .......... .......... .......... 98%  260K 1s

 8850K .......... .......... .......... .......... .......... 98%  329K 0s

 8900K .......... .......... .......... .......... .......... 99%  433K 0s

 8950K .......... .......... .......... .......... ......... 100%  331K=31s

2017-01-13 13:16:59 (288 KB/s) - written to stdout [9215609/9215609]

The file is updated, line after line, during the whole download process. Well, I need to get only the percentage: 0, 1, 2 ... 99 and nothing more.

The following script do the job, even if not perfectly:

tail -n 5 chk | tail -n 1 | colrm 1 63 | cut -d '%' -f 1

The problem arises when I need to do the same into a bash script, as in the following:

#!/bin/bash
# Test script for getting the percentage number from 'wget' output
i=0
wget -O - http://website/file > /dev/null 2>chk &
sleep 1

while (( $i < 90 ))
do
i=`tail -n 5 chk | tail -n 1 | colrm 1 63 | cut -d '%' -f 1`
echo $i
done

The script starts getting the wanted file, it writes out the chk file, but stops with the error message:

line 9: ((: < 90 : syntax error: operand expected (error token is "< 90 ")

I have tried by using [[ ]], quotes... but doesn't work.

Any idea here to do a better job?


Solution

  • Progress bar with wget, whiptail and GNU sed:

    wget --progress=dot 'URL' 2>&1 | sed -un 's/.* \([0-9]\+\)% .*/\1/p' | whiptail --gauge "Download" 7 50 0