How to add a progress bar to a shell script?

后端 未结 30 2230
情歌与酒
情歌与酒 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:35

    In case you have to show a temporal progress bar (by knowing in advance the showing time), you can use Python as follows:

    #!/bin/python
    from time import sleep
    import sys
    
    if len(sys.argv) != 3:
        print "Usage:", sys.argv[0], "", ""
        exit()
    
    TOTTIME=float(sys.argv[1])
    BARSIZE=float(sys.argv[2])
    
    PERCRATE=100.0/TOTTIME
    BARRATE=BARSIZE/TOTTIME
    
    for i in range(int(TOTTIME)+1):
        sys.stdout.write('\r')
        s = "[%-"+str(int(BARSIZE))+"s] %d%% "
        sys.stdout.write(s % ('='*int(BARRATE*i), int(PERCRATE*i)))
        sys.stdout.flush()
        SLEEPTIME = 1.0
        if i == int(TOTTIME): SLEEPTIME = 0.1
        sleep(SLEEPTIME)
    print ""
    

    Then, assuming you saved the Python script as progressbar.py, it's possible to show the progress bar from your bash script by running the following command:

    python progressbar.py 10 50
    

    It would show a progress bar sized 50 characters and "running" for 10 seconds.

提交回复
热议问题