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

时间:2019-05-23 02:58:28

标签: 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

1 个答案:

答案 0 :(得分:1)

当你看着

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

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