简体   繁体   English

如何每N秒重复运行bash脚本?

[英]How to repeatedly run bash script every N seconds?

I have a shell script printing some statistics like disk info, memory use and so on.我有一个 shell 脚本打印一些统计信息,如磁盘信息、memory 使用等。 But it shows information only once after the script runs and exits.但它只在脚本运行和退出后显示一次信息。 Can I make this script be run repeatedly (like htop for example) or something like that?我可以让这个脚本重复运行(例如htop )或类似的东西吗? I want this info to be updated every 5-10 seconds.我希望此信息每 5-10 秒更新一次。

In linux you can use the watch program to repeat an action. 在linux中,您可以使用watch程序重复操作。 Assuming that script.sh is executable: 假设script.sh是可执行的:

watch -n 10 path/to/script.sh

Would run it every 10 seconds. 会每10秒运行一次。

To make your script executable, you can use chmod +x script.sh . 要使脚本可执行,可以使用chmod +x script.sh Don't forget to add the shebang 别忘了添加shebang

#!/bin/bash

to the first line (assuming that it's a bash script). 到第一行(假设它是一个bash脚本)。

If you're running the script from your current directory, you can then do: 如果您从当前目录运行脚本,则可以执行以下操作:

watch -n 10 ./script.sh

A slight improvement to my comment: if your script exits with true (eg when it ends with exit 0 ), you can run 我的评论略有改进:如果您的脚本以true退出(例如,当它以exit 0出头结束时),您可以运行

while script; do sleep 10; done

This is the canonical way to repeat a command as long as it doesn't fail. 这是重复命令的规范方法,只要它不会失败。

As mentioned in a comment you need to wrap the script in an unconditional loop: 如评论中所述,您需要将脚本包装在无条件循环中:

while :; do script; sleep 10; done

Depending on the script logic instead of the sleep 10 you may want to put different for instance the read - for the input data on the file/socket stdin. 根据脚本逻辑而不是sleep 10,您可能希望将不同的例如读取 - 用于文件/套接字stdin上的输入数据。 This will assure you script will not wake until some data to process will be present and if the data will be present the script will not take any time to wake. 这将确保您在脚本不会被唤醒,直到某些要处理的数据存在,并且如果数据存在,脚本将不会花费任何时间来唤醒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM