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

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

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

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

有没有更简洁的方法呢?


当前回答

脚本文件

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 _ in {1..10}; do command; done   

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

另一种简单的破解方法:

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 i in 1 2 3; do
  some commands
done

和@joe- kobberg的回答很相似。他的更好,特别是当你需要很多重复的时候,只是更难记住其他语法,因为在过去的几年里,我不经常使用bash。我的意思是至少不是写脚本。

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

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