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

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

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

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

有没有更简洁的方法呢?


当前回答

使用常量:

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

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

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

其他回答

还有另一个答案:在空参数上使用参数展开:

# calls curl 4 times 
curl -s -w "\n" -X GET "http:{,,,}//www.google.com"

在Centos 7和MacOS上测试。

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 ((n=0;n<10;n++)); do
    some_command; 
done

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

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

如果你的范围有一个变量,使用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

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