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

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

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

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

有没有更简洁的方法呢?


当前回答

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

其他回答

另一种简单的破解方法:

seq 20 | xargs -Iz echo "Hi there"

执行echo命令20次。


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

大家好! 大家好 ...

脚本文件

bash-3.2$ cat test.sh 
#!/bin/bash

echo "The argument is  arg: $1"

for ((n=0;n<$1;n++));
do
  echo "Hi"
done

下面是输出

bash-3.2$  ./test.sh 3
The argument is  arg: 3
Hi
Hi
Hi
bash-3.2$

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。

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

你的例子的另一种形式:

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