-2

I have a bash script with a function named speedtest created like this:

function speedtest
    {
            echo $time_min; 
            echo $(date +%R),"$(speedtest-cli --csv)" >>temp.csv # Outputs van datum en speedtest in temp.csv
            cut -d, -f1,8 < temp.csv >> output2.csv; # Verwijderd onnodige info uit temp en plaatst het in output.csv
            awk -F , -v OFS=, '$3/=1000000' <output2 >output2.csv # Zet bits/s om naar Mbp/s
            rm temp.csv;
    }

I would like to run this function every x minutes.

Cyber_Star
  • 105
  • 1
  • I've done it before with a delay after the speedtest commando but the problem is that the time is the delay + the amout of time the script takes to run and i just want it to run every x minutes – Cyber_Star Dec 17 '17 at 10:46
  • Have you tried using crontab? – jesse_b Dec 17 '17 at 11:01
  • 3
    Cross-posted on https://askubuntu.com/questions/987063/run-bash-function-every-x-minutes – janos Dec 17 '17 at 11:48

1 Answers1

3

function speedtest { is the ksh function definition syntax. You might as well use ksh93 here whose $SECONDS can be made floating point and has a builtin sleep command with subsecond precision:

min=60
((every = 5 * min))
typeset -F SECONDS=0
t=0
while true; do
  speedtest
  sleep "$(( (t += every) - SECONDS))"
done

ksh93 also has builtin time stamping and CSV parsing/generation, so your speedtest function, could be written there as:

function speedtest
{
  typeset -a fields
  echo "$time_min"
  speedtest-cli --csv | IFS=, read -rSA fields
  ((fields[1] /= 1e6))
  {
    printf '%(%R)T'
    printf ',%#q' "${fields[@]:0:7}"
    printf '\n'
  } > output.csv
}

zsh's $SECONDS can also be made floating point, but sleep is not builtin there, so the same wouldn't work on systems where sleep doesn't support subsecond sleeping. It does have a zselect builtin though which can be used to sleep for fractions of seconds (centiseconds)