Skip to main content

Increment a variable timely in bash script [Resolved]

I want to increment a variable by one every 3 seconds. Is there any way to do that using bash?

I had a program running in infinite loop in which I am doing some stuff with a variable; I want to increment that variable, say, every 3 seconds, I am not supposed to use sleep.


Question Credit: charan priyatham
Question Reference
Asked September 19, 2019
Posted Under: Unix Linux
14 views
3 Answers

A horrible solution:

#!/bin/bash
somevar=0
somefile=$(mktemp)
echo "$somevar" > "$somefile"
while true; do sleep 3; ((somevar++)); echo "$somevar" > "$somefile" ;done &

  while true; do

    sleep 1
    avar="$(cat "$somefile")"
    echo "my var has value $avar"

  done

Certainly NOT precise with the times and NOWHERE near realtime-ready...


credit: markgraf
Answered September 19, 2019

Below is code

 i=10
    for ((j=1;j<=count_of_sequence;j++)); do echo $i; sleep 10;i=$(($i+1)); done

output

10
11
12
13
14

credit: Praveen Kumar BS
Answered September 19, 2019
Your Answer