'For' 循环并在 Bash 脚本中休眠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22830973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'For' loop and sleep in a Bash script
提问by Tomas
I have a Bash script with a for
loop, and I want to sleep for X seconds.
我有一个带for
循环的 Bash 脚本,我想睡 X 秒。
#!/bin/sh
for i in `seq 8`;
do ssh w$i 'uptime;
ps -elf|grep httpd|wc -l;
free -m;
mpstat';
done &
pid=$!
kill -9 $pid
In Bash: sleep 2
sleeps for two seconds. How can I kill the pid automatically after two seconds?
在 Bash 中:sleep 2
休眠两秒钟。如何在两秒钟后自动终止 pid?
采纳答案by Mathias
Like suggested in the comments
喜欢评论中的建议
#!/bin/sh
for i in `seq 8`;
do ssh w$i 'uptime;
ps -elf|grep httpd|wc -l;
free -m;
mpstat';
done &
pid=$!
sleep 2
kill -9 $pid
In this version, one ssh process may stay alive forever. So maybe it would be better to kill each ssh command separately:
在这个版本中,一个 ssh 进程可能永远活着。所以也许最好分别杀死每个 ssh 命令:
#!/bin/sh
for i in `seq 8`;
do ssh w$i 'uptime;
ps -elf|grep httpd|wc -l;
free -m;
mpstat' &;
pid=$!
sleep 0.3
kill $pid
done
回答by drkunibar
You need to put your loop in a wrapper:
您需要将循环放入包装器中:
Your script(I call it foo.sh
)
你的脚本(我称之为foo.sh
)
#!/bin/sh
for i in `seq 8`;
do ssh w$i 'uptime;
ps -elf|grep httpd|wc -l;
free -m;
mpstat';
done
The wrapper
包装纸
#!/bin/sh
foo.sh &
pid=$!
sleep 3 #sleep takes number of seconds
kill $pid
You also can check if your process already exists by ps -p $pid -o pid | grep $pid
您还可以通过以下方式检查您的进程是否已经存在 ps -p $pid -o pid | grep $pid