我偶尔会像这样运行bash命令行:

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

在一行中运行some_command多次——在本例中为10次。

通常some_command实际上是一个命令链或管道。

有没有更简洁的方法呢?


当前回答

你的例子的另一种形式:

n=0; while (( n++ < 10 )); do some_command; done

其他回答

Xargs和seq会有所帮助

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

视图:

abon@abon:~$ __run_times 3  echo hello world
hello world
hello world
hello world

此命令可重复执行此命令10次或更多次

for i in {1..10}; do **your command**; done

例如

for i in {1..10}; do **speedtest**; done

首先,你可以把它封装在一个函数中:

function manytimes {
    n=0
    times=$1
    shift
    while [[ $n -lt $times ]]; do
        $@
        n=$((n+1))
    done
}

这样称呼它:

$ manytimes 3 echo "test" | tr 'e' 'E'
tEst
tEst
tEst

我用这个循环来求解,其中repeat是一个整数,表示循环的个数

repeat=10
for n in $(seq $repeat); 
    do
        command1
        command2
    done
for _ in {1..10}; do command; done   

注意使用下划线而不是变量。