如何编写一个小 Bash shell 脚本来每 5 秒重复一次操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4502476/
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-09 19:59:41  来源:igfitidea点击:

How can I write a tiny Bash shell script to repeat an action every 5 seconds?

bashshellscriptingrepeat

提问by Alan H.

I want to copy a file from one location to another every five seconds. I don't want to set up a cronjob because this is only temporary and needs to be fully under my control.

我想每五秒钟将一个文件从一个位置复制到另一个位置。我不想设置 cronjob,因为这只是暂时的,需要完全在我的控制之下。

Can I write a .sh that will do this?

我可以写一个 .sh 来做到这一点吗?

(I'm on Mac OS X.)

(我使用的是 Mac OS X。)

回答by Sage Mitchell

The watch command is a good option. If you end up needing more control you can use a while loop:

watch 命令是一个不错的选择。如果您最终需要更多控制,您可以使用 while 循环:

while [ 1 ]
do
  cp source dest
  sleep 5s
done

回答by David Yaw

while true
do
    cp file /other/location
    sleep 5
done

You don't even need to write a script for this, just type while true; do cp file /other/location; sleep 5; doneat the bash prompt.

您甚至不需要为此编写脚本,只需while true; do cp file /other/location; sleep 5; done在 bash 提示符下键入即可。

回答by barti_ddu

Perhaps watchwill do:

也许watch会做:

watch -n 5 date

回答by ngen

Use the watchcommand.

使用watch命令。

Source

来源

回答by Sean

not sure if this will work, but you could try it, basically it is an infinite loop, so you would have to terminate the script manually or add a filter for say the q key, when pressed sets copyFiles to 0

不确定这是否可行,但您可以尝试一下,基本上它是一个无限循环,因此您必须手动终止脚本或为 q 键添加过滤器,按下时将 copyFiles 设置为 0

copyFile = 1
while [ ${copyFile} -eq 1 ]
do
    echo "Copying file..."
    cp file /other/location
    echo "File copied.  Press q to quit."
    read response
    [ "$response" = "q" ] && copyFile = 0
    sleep 5
done