Is there a better way to run a command N times in bash?

后端 未结 19 2106
执笔经年
执笔经年 2020-11-28 00:26

I occasionally run a bash command line like this:

n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done

To run some_command

相关标签:
19条回答
  • 2020-11-28 01:19

    A simple function in the bash config file (~/.bashrc often) could work well.

    function runx() {
      for ((n=0;n<$1;n++))
        do ${*:2}
      done
    }
    

    Call it like this.

    $ runx 3 echo 'Hello world'
    Hello world
    Hello world
    Hello world
    
    0 讨论(0)
  • 2020-11-28 01:22

    xargs and seq will help

    function __run_times { seq 1 $1| { shift; xargs -i -- "$@"; } }
    

    the view :

    abon@abon:~$ __run_times 3  echo hello world
    hello world
    hello world
    hello world
    
    0 讨论(0)
  • 2020-11-28 01:23

    How about the alternate form of for mentioned in (bashref)Looping Constructs?

    0 讨论(0)
  • 2020-11-28 01:24
    for run in {1..10}
    do
      command
    done
    

    Or as a one-liner for those that want to copy and paste easily:

    for run in {1..10}; do command; done
    
    0 讨论(0)
  • 2020-11-28 01:24

    If you are OK doing it periodically, you could run the following command to run it every 1 sec indefinitely. You can put other custom checks in place to run it n number of times.

    watch -n 1 some_command

    If you wish to have visual confirmation of changes, append --differences prior to the ls command.

    According to the OSX man page, there's also

    The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. The -t or --no-title option turns off the header showing the interval, command, and current time at the top of the display, as well as the following blank line.

    Linux/Unix man page can be found here

    0 讨论(0)
  • 2020-11-28 01:26

    If you're using the zsh shell:

    repeat 10 { echo 'Hello' }
    

    Where 10 is the number of times the command will be repeated.

    0 讨论(0)
提交回复
热议问题