如何在 bash 中使用 mod 运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5688576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:25:25  来源:igfitidea点击:

How to use mod operator in bash?

bashmoduloarithmetic-expressions

提问by Eric

I'm trying a line like this:

我正在尝试这样的一行:

for i in {1..600}; do wget http://example.com/search/link $i % 5; done;

What I'm trying to get as output is:

我试图获得的输出是:

wget http://example.com/search/link0
wget http://example.com/search/link1
wget http://example.com/search/link2
wget http://example.com/search/link3
wget http://example.com/search/link4
wget http://example.com/search/link0

But what I'm actually getting is just:

但我实际得到的只是:

    wget http://example.com/search/link

回答by Mark Longair

Try the following:

请尝试以下操作:

 for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done

The $(( ))syntax does an arithmetic evaluationof the contents.

$(( ))语法做一个算术评估的内容。

回答by Chris Eberle

for i in {1..600}
do
    n=$(($i%5))
    wget http://example.com/search/link$n
done

回答by Higor E.

You must put your mathematical expressions inside $(( )).

您必须将数学表达式放在 $(( )) 中。

One-liner:

单线:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

多行:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

回答by h__

This might be off-topic. But for the wget in for loop, you can certainly do

这可能是题外话。但是对于 for 循环中的 wget,你当然可以做到

curl -O http://example.com/search/link[1-600]