How to Use Mod Operator in Bash?

How to Use Mod Operator in Bash?

I'm trying a line like this:

for i in {1..600}; do wget  $i % 5; done;

What I'm trying to get as output is:

wget 
wget 
wget 
wget 
wget 
wget 

But what I'm actually getting is just:

    wget 

6 Answers

Try the following:

 for i in {1..600}; do echo wget (($i % 5)); done

The $(( )) syntax does an arithmetic evaluation of the contents.

2
for i in {1..600}
do
    n=$(($i%5))
    wget 
done
1

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

One-liner:

for i in {1..600}; do wget (($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget (($i % 5))
done
1

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

curl -O 

This post is rather old but I thought I would contribute since I stumbled upon it while trying to research the same issue of setting keyboard color through automation.

I created a simple BASH script that I call from my ROOT chrontab every minute to set the keyboard color as the day progresses. You can tweak the color patterns and the modulo to match your needs. This is just a good starting point.

#!/bin/bash
# must run as ROOT to work
# put in your root crontab to change the color at set times

sec=$(date +%s)
min=$(( $sec / 60 ))
col=$(( $min % 7 ))
colors=('0000FF' '00FF00' '00FFFF' 'FF0000' 'FF00FF' 'FFFF00' 'FFFFFF')
colorFile="/sys/class/leds/system76_acpi::kbd_backlight/color"

if [ -f "$colorFile" ]; then
    echo "Set keyboard to color $col ~ ${colors[$col]}"
    echo "${colors[$col]}" > "$colorFile"
fi

Hope you like it.

How to use all bash operators, and arithmetic expansion, in bash

Of the 346k visitors to this question thus far, I'd be willing to bet 344.9k of them just want the title of this question answered 😃:

How to use mod operator in bash?

Even I googled "bash modulus" looking for that answer, and landed here. So, now that I've figured it out, let's just jump straight to it:

How to use the modulus (%) operator in bash

Just do this, for instance:

# 7 mod 4 (answer is 3, but to print the output you must use one of the cmds
# below)
$((7 % 4))

# [PREFERRED: no quotes]
# print the result (double quotes are not required)
echo $((7 % 4))

# print the result (with double quotes if you like)
echo "$((7 % 4))"

Example with variables:

num1="7"
num2="4"

# [PREFERRED: no $ signs nor extraneous quotes] result is 3
echo $((num1 % num2))

# Also ok: with $ signs
echo $(($num1 % $num2))

# Also ok: with $ signs and extra quotes
echo "$(("$num1" % "$num2"))"

Store the result into a variable:

mod=$((num1 % num2))
echo "$mod"  # result is 3

The main links to study for these concepts are these, from the official GNU bash user manual:

  1. Bash Arithmetic Expansion
  2. Bash Shell Arithmetic
James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.