以毫秒为单位的 Bash 睡眠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32210152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:04:40  来源:igfitidea点击:

Bash sleep in milliseconds

bashtimersleep

提问by Noqrax

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

我需要一个以毫秒为单位的计时器。我尝试sleep 0.1在脚本中使用命令,但看到以下错误消息:

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

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

When I run sleep 0.1in terminal it works fine.

当我sleep 0.1在终端中运行时,它工作正常。

Please help me!

请帮我!

EDIT: Sorry I have made a mistake:

编辑:对不起,我犯了一个错误:

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

Line sleep 0.1was 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:

sleep 0.1是第 5 行和SECS=$[$SECS-0.1]第 6 行。我只是乱码。问题出在第 6 行,因为 bash 不能处理浮点数。我改变了我的功能如下:

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

回答by kenorb

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

确保您在 Bash 中运行脚本,而不是/bin/sh. 例如:

#!/usr/bin/env bash
sleep 0.1

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

换句话说,尝试明确指定 shell。然后通过以下方式运行:./foo.shbash foo.sh

In case, sleepis an alias or a function, try replacing sleepwith \sleep.

如果sleep是别名或函数,请尝试替换sleep\sleep

回答by Jose H. Rosa

Some options:

一些选项:

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

or

或者

read -p "Continuing in 0.5 Seconds...." -t 0.5
echo "Continuing ...."

回答by Evhz

Bash was complaining about decimal values,

Bash 抱怨十进制值,

read: 0.5: invalid timeout specification

读取:0.5:无效的超时规范

I came around with thissolution which works great.

我想到了这个效果很好的解决方案。

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

sleep_fraction 0.01428