如何在fish shell中运行命令n次?

ber*_*esh 0 shell fish

Fish文档提供了以下运行for循环的方法。

for i in 1 2 3 4 5;
    echo $i
end
Run Code Online (Sandbox Code Playgroud)

假设我想运行一个命令 1000 次,我该怎么做?

Mar*_*ler 6

相同的文档,https://fishshell.com/docs/current/language.html#loops-and-blocks

for i in (seq 1 5)
    echo $i
end
Run Code Online (Sandbox Code Playgroud)

替换seq 1 5为您想要获取的数字,例如seq 14 1000获取从 14 到 1000 的数字;如果想从1开始,可以省略起始点,即写成seq 1000

顺便说一句,这就像非常经典的 UNIX shell;感觉不是很现代。(在bashand zshyou can do中for i in {1..1000},我认为这更容易、更清晰地阅读,更不用说它节省了实际运行外部程序seq并缓冲其输出的时间。)

另一种不依赖 coreutils 的方法(如果你不是 GNU 程序也不是 POSIX shell,那么依赖 coreutils 是一件令人悲伤的事情),将使用循环while和纯粹的 Fish 内置函数:

set counter 0
# -lt: less than
while test $counter -lt 1000;
    set counter (math $counter + 1)
    echo $counter
end
Run Code Online (Sandbox Code Playgroud)


ber*_*esh 5

事实证明,gnu-coreutils 中有一个程序seq可以打印出一系列数字。

因此,要运行命令 n 次,可以使用以下循环。

for i in (seq n);
    echo $i
end
Run Code Online (Sandbox Code Playgroud)