首页 > 解决方案 > 在 shell 脚本中每秒运行一个 for 循环

问题描述

我试图每秒运行一个程序

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

标签: linuxshell

解决方案


当你看

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

您可以看到tt.sh使用 pid 10455 启动了另外两个进程。
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

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


推荐阅读