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

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

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

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

有没有更简洁的方法呢?


当前回答

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

repeat=10
for n in $(seq $repeat); 
    do
        command1
        command2
    done

其他回答

如果你正在使用zsh shell:

repeat 10 { echo 'Hello' }

其中10是命令将被重复执行的次数。

如果你的范围有一个变量,使用seq,像这样:

count=10
for i in $(seq $count); do
    command
done

简单:

for run in {1..10}; do
  command
done

或者作为一行程序,供那些想要轻松复制和粘贴的人使用:

for run in {1..10}; do command; done

使用常量:

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

使用变量(可以包括数学表达式):

x=10; for ((n=0; n < (x / 2); n++)); do some_command; done

Xargs速度很快:

#!/usr/bin/bash
echo "while loop:"
n=0; time while (( n++ < 10000 )); do /usr/bin/true ; done

echo -e "\nfor loop:"
time for ((n=0;n<10000;n++)); do /usr/bin/true ; done

echo -e "\nseq,xargs:"
time seq 10000 | xargs -I{} -P1 -n1 /usr/bin/true

echo -e "\nyes,xargs:"
time yes x | head -n10000 |  xargs -I{} -P1 -n1 /usr/bin/true

echo -e "\nparallel:"
time parallel --will-cite -j1 -N0 /usr/bin/true ::: {1..10000}

在现代64位Linux上,给出:

while loop:

real    0m2.282s
user    0m0.177s
sys     0m0.413s

for loop:

real    0m2.559s
user    0m0.393s
sys     0m0.500s

seq,xargs:

real    0m1.728s
user    0m0.013s
sys     0m0.217s

yes,xargs:

real    0m1.723s
user    0m0.013s
sys     0m0.223s

parallel:

real    0m26.271s
user    0m4.943s
sys     0m3.533s

这是有意义的,因为xargs命令是一个单独的本机进程,多次生成/usr/bin/true命令,而不是在Bash中解释的for和while循环。当然,这只适用于单个命令;如果你需要在每次循环迭代中执行多个命令,它将和传递sh -c 'command1;command2;...'到xargs

也可以将-P1改为-P8,以并行生成8个进程,从而获得另一个巨大的速度提升。

我不知道GNU并行为什么这么慢。我本以为它可以与xargs相媲美。

For循环可能是正确的方法,但这里有一个有趣的替代方法:

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

如果需要迭代数作为调用的参数,请使用:

Echo -e {1..10}"\n" |xargs -I@ echo现在我正在运行迭代@

编辑:上面给出的解决方案只能通过简单的命令运行(没有管道等)才能顺利工作,这是正确的评论。您总是可以使用sh -c来做更复杂的事情,但不值得这样做。

我通常使用的另一种方法是以下函数:

Rep () {s=$1;shift;e=$1;shift;对于x在' seq $s $e ';执行c=${@//@/$x};完成;}

现在你可以把它称为:

代表3 10回声迭代@

前两个数字给出了范围。@将被转换为迭代号。现在你也可以在管道中使用这个:

代表1 10 "ls R@/|wc -l"

给出R1目录下的文件数。R10。