我偶尔会像这样运行bash命令行:
n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done
在一行中运行some_command多次——在本例中为10次。
通常some_command实际上是一个命令链或管道。
有没有更简洁的方法呢?
我偶尔会像这样运行bash命令行:
n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done
在一行中运行some_command多次——在本例中为10次。
通常some_command实际上是一个命令链或管道。
有没有更简洁的方法呢?
当前回答
此命令可重复执行此命令10次或更多次
for i in {1..10}; do **your command**; done
例如
for i in {1..10}; do **speedtest**; done
其他回答
还有另一个答案:在空参数上使用参数展开:
# calls curl 4 times
curl -s -w "\n" -X GET "http:{,,,}//www.google.com"
在Centos 7和MacOS上测试。
如果你的范围有一个变量,使用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
首先,你可以把它封装在一个函数中:
function manytimes {
n=0
times=$1
shift
while [[ $n -lt $times ]]; do
$@
n=$((n+1))
done
}
这样称呼它:
$ manytimes 3 echo "test" | tr 'e' 'E'
tEst
tEst
tEst
脚本文件
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。我的意思是至少不是写脚本。