How to add a progress bar to a shell script?

后端 未结 30 2959
情歌与酒
情歌与酒 2020-11-22 05:48

When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.

For example, copying a b

30条回答
  •  面向向阳花
    2020-11-22 06:28

    My solution displays the percentage of the tarball that is currently being uncompressed and written. I use this when writing out 2GB root filesystem images. You really need a progress bar for these things. What I do is use gzip --list to get the total uncompressed size of the tarball. From that I calculate the blocking-factor needed to divide the file into 100 parts. Finally, I print a checkpoint message for each block. For a 2GB file this gives about 10MB a block. If that is too big then you can divide the BLOCKING_FACTOR by 10 or 100, but then it's harder to print pretty output in terms of a percentage.

    Assuming you are using Bash then you can use the following shell function

    untar_progress () 
    { 
      TARBALL=$1
      BLOCKING_FACTOR=$(gzip --list ${TARBALL} |
        perl -MPOSIX -ane '$.==2 && print ceil $F[1]/50688')
      tar --blocking-factor=${BLOCKING_FACTOR} --checkpoint=1 \
        --checkpoint-action='ttyout=Wrote %u%  \r' -zxf ${TARBALL}
    }
    

提交回复
热议问题