我偶尔会像这样运行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实际上是一个命令链或管道。
有没有更简洁的方法呢?
当前回答
你的例子的另一种形式:
n=0; while (( n++ < 10 )); do some_command; done
其他回答
for _ in {1..10}; do command; done
注意使用下划线而不是变量。
bash配置文件中的一个简单函数(~/。Bashrc经常)可以很好地工作。
function runx() {
for ((n=0;n<$1;n++))
do ${*:2}
done
}
这样叫它。
$ runx 3 echo 'Hello world'
Hello world
Hello world
Hello world
首先,你可以把它封装在一个函数中:
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
另一种简单的破解方法:
seq 20 | xargs -Iz echo "Hi there"
执行echo命令20次。
注意seq 20 | xargs -Iz echo“Hi there z”将输出:
大家好! 大家好 ...
在(bashref)循环构造中提到的for的替代形式如何?