linux - 在 shell 脚本中每秒运行一次 for 循环

标签 linux shell

我试图每秒运行一个程序

for i in {1..3}
do
        echo $i `date`
        ./tt.sh $i &
        sleep 1
done

for循环实际上在后台触发了9个循环,有没有办法让程序每秒运行一次

下面是进程信息

root     10455     1  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1
root     10458 10455  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1
root     10460 10455  3 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1
root     10692     1  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 2
root     10699 10692  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 2
root     10701 10692  2 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 2
root     10943     1  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 3
root     10953 10943  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 3
root     10955 10943  2 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 3

最佳答案

当你看

root     10455     1  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1
root     10458 10455  0 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1
root     10460 10455  3 23:44 pts/0    00:00:00 /bin/bash ./tt.sh 1

您可以看到 pid 10455 的 tt.sh 启动了另外两个进程。
tt.sh 已被您的循环启动了 3 次,您可以查看 tt.sh 以了解它为何会产生其他进程。

通过下面的代码,您可以看到脚本仅启动程序 3 次:

for i in {101..103}
do
        echo $i `date`
        sleep $i &
        sleep 1
done

ps -ef 将显示

username    39     1  0 09:05 pts/0    00:00:00 sleep 101
username    42     1  0 09:05 pts/0    00:00:00 sleep 102
username    45     1  0 09:05 pts/0    00:00:00 sleep 103

如果您不希望它们同时运行,请删除 &

关于linux - 在 shell 脚本中每秒运行一次 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267495/

相关文章:

linux - 从 root 运行一个脚本,它调用 sudo oracle 中的另一个脚本。如何在不询问 oracle 密码的情况下做到这一点

perl - 如何正确捕获unix命令的返回值?

linux - Docker 运行,设备上没有剩余空间

java - Xlib:使用 XAddToChangeSet 向保存集添加窗口在 Java/JNI 中不起作用

linux - 为什么我不能重定向标准输出/错误以登录 Linux

linux - Glob 是不同的值错误打开文件和读取

shell - 如何使失败的 $(shell) 命令中断

linux - 使用shell脚本自动化scp网站文件传输

linux - 如何在 shell 中保留 $

Linux shell 脚本来计算文件并在超过数量时删除