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

后端 未结 19 2315
执笔经年
执笔经年 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:09

    For loops are probably the right way to do it, but here is a fun alternative:

    echo -e {1..10}"\n" |xargs -n1 some_command

    If you need the iteration number as a parameter for your invocation, use:

    echo -e {1..10}"\n" |xargs -I@ echo now I am running iteration @

    Edit: It was rightly commented that the solution given above would work smoothly only with simple command runs (no pipes, etc.). you can always use a sh -c to do more complicated stuff, but not worth it.

    Another method I use typically is the following function:

    rep() { s=$1;shift;e=$1;shift; for x in `seq $s $e`; do c=${@//@/$x};sh -c "$c"; done;}

    now you can call it as:

    rep 3 10 echo iteration @

    The first two numbers give the range. The @ will get translated to the iteration number. Now you can use this with pipes too:

    rep 1 10 "ls R@/|wc -l"

    with give you the number of files in directories R1 .. R10.

提交回复
热议问题