在Linux中自动重复命令

本文介绍了在Linux环境下如何设置命令以固定间隔时间自动重复执行的方法。包括使用watch命令每5秒更新ls-l命令的输出,展示文件大小变化;利用while循环结合sleep实现自定义时间间隔的命令重复执行;以及如何通过过滤只显示特定信息。适用于系统监控、文件状态检查等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Repeat command automatically in Linux

Is it possible in linux command line to have a command repeat every n seconds. 是否有可能在linux命令行中每n秒重复一次命令。

For example, say I have an import running and i am doing 例如,假设我有一个导入运行,我正在做

ls -l

to check the file size is increasing. 检查文件大小是否增加。 I would like to have a command to have this automatically repeat. 我想有一个命令让它自动重复。


#1楼

参考:https://stackoom.com/question/v2MN/在Linux中自动重复命令


#2楼

Watch every 5 seconds ... 每5秒观看一次......

watch -n 5 ls -l

If you wish to have visual confirmation of changes, append --differences prior to the ls command. 如果您希望直观地确认更改, --differencesls命令之前附加--differences

According to the OSX man page, there's also 根据OSX手册页,还有

The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. - 累积选项使突出显示为“粘性”,呈现所有已更改位置的运行显示。 The -t or --no-title option turns off the header showing the interval, command, and current time at the top of the display, as well as the following blank line. -t或--no-title选项将关闭显示显示顶部的间隔,命令和当前时间的标题,以及以下空白行。

Linux/Unix man page can be found here Linux / Unix手册页可以在这里找到


#3楼

while true; do
    sleep 5
    ls -l
done

#4楼

You can run the following and filter the size only. 您可以运行以下内容并仅过滤大小。 If your file was called somefilename you can do the following 如果您的文件名为somefilename ,则可以执行以下操作

while :; do ls -lh | awk '/some*/{print $5}'; sleep 5; done

One of the many ideas. 众多想法之一。


#5楼

"watch" does not allow fractions of a second in Busybox, while "sleep" does. “观看”不允许在Busybox中使用一秒钟,而“睡眠”则可以。 If that matters to you, try this: 如果这对您很重要,请尝试以下方法:

while true; do ls -l; sleep .5; done

#6楼

如果您想要执行特定次数的操作,您可以随时执行此操作:

repeat 300 do my first command here && sleep 1.5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值