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

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

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

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

有没有更简洁的方法呢?


当前回答

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

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

其他回答

另一种简单的破解方法:

seq 20 | xargs -Iz echo "Hi there"

执行echo命令20次。


注意seq 20 | xargs -Iz echo“Hi there z”将输出:

大家好! 大家好 ...

所有现有的答案似乎都需要bash,并且不能使用标准的BSD UNIX /bin/sh(例如,OpenBSD上的ksh)。

下面的代码可以在任何BSD上运行:

$ echo {1..4}
{1..4}
$ seq 4
sh: seq: not found
$ for i in $(jot 4); do echo e$i; done
e1
e2
e3
e4
$

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

bash配置文件中的一个简单函数(~/。Bashrc经常)可以很好地工作。

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

这样叫它。

$ runx 3 echo 'Hello world'
Hello world
Hello world
Hello world

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。