我偶尔会运行这样的一个bash命令行:
n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done
要连续运行some_command
多次 - 在这种情况下为10次。
通常some_command
是一系列命令或管道。
是否有更简洁的方法来做到这一点?
首先,你可以将它封装在一个函数中:
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
tr
是误导性的,它是在 manytimes
的输出上工作,而不是 echo
。我认为你应该从示例中删除它。 - Dmitry Ginzburgxargs和seq会有所帮助
function __run_times { seq 1 $1| { shift; xargs -i -- "$@"; } }
视图:
abon@abon:~$ __run_times 3 echo hello world
hello world
hello world
hello world
我用以下循环解决了问题,其中repeat是代表循环次数的整数。
repeat=10
for n in $(seq $repeat);
do
command1
command2
done
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上进行了测试。
for i in 1 2 3; do
some commands
done
与@joe-koberg的答案非常相似。如果您需要多次重复,他的方法更好,但对我来说更难记住其他语法,因为在过去的几年中,我没有经常使用bash
,至少不是用于脚本编写。
使用for循环可能是正确的方法,但这里有一个有趣的替代方案:
echo -e {1..10}"\n" |xargs -n1 some_command
如果您需要迭代号作为调用参数,请使用:
echo -e {1..10}"\n" |xargs -I@ echo now I am running iteration @
编辑: 正确地评论了上面给出的解决方案只能平稳地运行简单命令(没有管道等)。 您总是可以使用sh -c
来执行更复杂的操作,但不值得。
我通常使用的另一种方法是以下函数:
rep() { s=$1;shift;e=$1;shift; for x in `seq $s $e`; do c=${@//@/$x};sh -c "$c"; done;}
现在你可以这样调用它:
rep 3 10 echo iteration @
前两个数字给出范围。 @
将被转换为迭代号。 现在你也可以将其与管道一起使用:
rep 1 10 "ls R@/|wc -l"
将会给出目录R1 .. R10中文件的数量。
rep 1 2 touch "foo @"
不会创建两个名为 "foo 1" 和 "foo 2" 的文件,而是会创建三个文件 "foo"、"1" 和 "2"。使用 printf
和 %q
可能可以正确引用,但是将任意单词序列正确引用为一个字符串传递给 sh -c
将会很棘手。 - chepner.bashrc
中定义了rep
的定义,进一步的调用就变得更加简洁。 - musiphilrep
将占用标准输入进行迭代,但没有充分的理由。为什么不像这样使用简单的for
循环:for ((x=$s; x<=$e; ++x)); do ...; done
? - musiphilbash-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$
let ++n
代替n=$((n+1))
(少3个字符)。 - musiphilzsh
有repeat 10 do some_command; done
。该命令可以重复执行某个命令10次。 - chepnersh:1:[[: not found
错误提示。 - bstpierre