Bash sleep in milliseconds

2019-04-05 04:07发布

I need a timer which will work with milliseconds. I tried to use sleep 0.1 command in script I see error message:

syntax error: invalid arithmetic operator (error token is ".1")

When I run sleep 0.1 in terminal it works fine.

Please help me!

EDIT: Sorry I have take an mistake:

function timer
{
while [[ 0 -ne $SECS ]]; do
    echo "$SECS.."
    sleep 0.1
    SECS=$[$SECS-0.1]
done
}

Line sleep 0.1 was 5th and SECS=$[$SECS-0.1] was 6th. I just garbled lines. The problem was in 6th line, because bash can't work with float numbers. I changed my function as below:

MS=1000
function timer
{
while [[ 0 -ne $MS ]]; do
    echo "$SECS.."
    sleep 0.1
    MS=$[$MS-100]
done
}

标签: bash timer sleep
3条回答
对你真心纯属浪费
2楼-- · 2019-04-05 04:36

Bash was complaining about decimal values,

read: 0.5: invalid timeout specification

I came around with this solution which works great.

sleep_fraction() {
  /usr/bin/perl -e "select(undef, undef, undef, $1)"
}

sleep_fraction 0.01428
查看更多
ら.Afraid
3楼-- · 2019-04-05 04:42

Make sure you're running your script in Bash, not /bin/sh. For example:

#!/usr/bin/env bash
sleep 0.1

In other words, try to specify the shell explicitly. Then run either by: ./foo.sh or bash foo.sh.

In case, sleep is an alias or a function, try replacing sleep with \sleep.

查看更多
ら.Afraid
4楼-- · 2019-04-05 04:50

Some options:

read -p "Pause Time .5 seconds" -t 0.5

or

read -p "Continuing in 0.5 Seconds...." -t 0.5
echo "Continuing ...."
查看更多
登录 后发表回答