0

we need to run the run.sh on each 10 steps

for x in {1..100} ; do
  sleep 1
  /tmp/run.sh
done

so finally run.sh will run 10 times

how we can do that?

other example ( in this case run.sh will run 20 times )

for x in {1..200} ; do
  sleep 1
  /tmp/run.sh
done
  • I supposed there are other stuff like sleep 1 that need to be run on all iterations ? – Archemar Feb 22 '18 at 14:22
4

You just have to test if the value of x can be divided by 10 :

for x in {0..100} ; do
    if (( x % 10 == 0 ))
    then
        /tmp/run.sh
    fi
    sleep 1
done
  • +1 for better bash. Using [ tests and (( )) at the same time looks weird – Gilles Quenot Feb 22 '18 at 14:16
4

This is a job for the modulus (%) operator. For example:

for x in {1..100} ; do
  sleep 1
  [ $((x % 10)) -eq 0 ] && /tmp/run.sh
done

Another example:

$ for i in {1..100} ; do  [ $((i % 10)) -eq 0 ] && echo $i  ; done
10
20
30
40
50
60
70
80
90
100
  • why i ? should be x – yael Feb 22 '18 at 14:15
  • because i tested it with $i in my shell and forgot to change it to $x here. fixed. – cas Feb 22 '18 at 14:16
  • Why using [ and (( )) at the same time ? Check @Félicien answer – Gilles Quenot Feb 22 '18 at 14:18
  • Personal style choice - i.e. because I wrote it and not someone else. It's syntactically valid and shorter. And, IMO, more readable. One may equally ask "why use if/then/else when [ ... ] && will do"? – cas Feb 22 '18 at 14:19
  • +1 for oneliner – Zdenek Hatak Nov 26 at 8:22
2
for (( i = 0; i < 10; ++i )); do
    /tmp/run.sh
    sleep 10
done

If you want to run the script ten times, then do the loop ten times and sleep the appropriate amount of time in-between.

Or, with a parameter determining how many times to run the script:

n=20
for (( i = 0; i < n; ++i )); do
    /tmp/run.sh
    sleep 10
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.