Convert floating point variable to integer?


The shell script shown below will show a warning if the page takes more than 6 seconds to load. The problem is that the myduration variable is not an integer. How do I convert it to integer?

myduration=$(curl -w %{time_total}) > /dev/null ; \
[[ $myduration -gt 1 ]] && echo "`date +'%y%m%d%H%M%S'

It took more than 6 seconds to load the page

3/9/2018 3:31:46 AM

Accepted Answer

Assuming $myduration is a decimal or integer

$ myduration=6.5
$ myduration=$( printf "%.0f" $myduration )
$ echo $myduration
9/1/2009 8:47:27 PM

Eliminate page contents from the variable:

When I tried your command, myduration contained the HTML contents of the page at the URL I used in my test plus the time value. By adding -s to suppress the progress bar and adding -o /dev/null to the options for curl, I was able to remove the redirect to /dev/null and have only the time saved in myduration.

Since the value of myduration is likely to be short, you can use the technique ire_and_curses shows which will often yield zero as its result which would be less than the 1 you are testing for (note that your log message says "6 seconds", though).

Finer resolution:

If you'd like to have a finer resolution test, you can multiply myduration by 1000 using a technique like this:

mult1000 () {
    local floor=${1%.*}
    [[ $floor = "0" ]] && floor=''
    local frac='0000'
    [[ $floor != $1 ]] && frac=${1#*.}$frac
    echo ${floor}${frac:0:3}

Edit: This version of mult1000 properly handles values such as "0.234", "1", "2.", "3.5" and "6.789". For values with more than three decimal places, the extra digits are truncated without rounding regardless of the value ("1.1119" becomes "1.111").

Your script with the changes I mentioned above and using mult1000 (with my own example time):

myduration=$(curl -s -o /dev/null -w %{time_total}); [[ $(mult1000 $myduration) -gt 3500 ]] && echo "`date +'%y%m%d%H%M%S'` took more than 3.5 seconds to load the page " >> /home/shantanu/speed_report.txt

Here it is broken into multiple lines (and simplified) to make it more readable here in this answer:

myduration=$(curl -s -o /dev/null -w %{time_total})
[[ $(mult1000 $myduration) -gt 3500 ]] &&
  echo "It took more than 3.5 seconds to load t" >> report.txt

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow