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


168

我正在尝试这样的一行:

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

我想要获得的输出是:

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

但是我实际上得到的只是:

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

Answers:


234

请尝试以下操作:

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

$(( ))语法对内容进行算术评估


4
如果有人需要这样的数学运算,需要注意的是负数模运算bash 只返回余数不是数学模的结果。这意味着,尽管数学上-12 mod 108,bash会将其计算为-2。您可以使用简单的echo $((-12 % 10))-2)测试它,并将其与python3 python3 -c "print(-12 % 10)"8)比较。
Lirt

1
别忘了算术构造$(())会自动扩展变量,因此您不需要$使用i。这$((i % 5))将很好地工作。
Yokai


30

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

单线:

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

多行:

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

13

这可能是题外话。但是对于wget for for循环,您当然可以

curl -O http://example.com/search/link[1-600]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.