具有基本 if/else 和基于模式运行的进程计数的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4103972/
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
Bash script with basic if/else and count of processes running based on a pattern
提问by Andy
I'm trying to write a script that counts the number of processes running matching a patern. If it exceeds a hardcoded value then do something...else do something else.
我正在尝试编写一个脚本来计算运行匹配模式的进程数。如果它超过了硬编码值,那么做点什么……否则做点别的。
I am finding out the count of processes using:
我正在使用以下方法找出进程数:
ps ax | grep process_name | wc -l | sed -e "s: ::g"
If the output of the above command is greater than 15..it should echo "Done". Otherwise, echo "Not Complete".
如果上述命令的输出大于 15..它应该回显“完成”。否则,回显“未完成”。
So far, I have this but it isn't working:
到目前为止,我有这个,但它不起作用:
numprocesses=ps ax | grep sms_queue | wc -l | sed -e "s: ::g"
if [ $numprocesses -le "15" ] ; then
echo "Done."
else
echo "Not Complete."
fi
回答by paxdiablo
numprocesses=$(ps ax | grep '[s]ms_queue' | wc -l)
if [[ $numprocesses -gt 15 ]] ; then
echo "Done."
else
echo "Not Complete."
fi
You had a few problems.
你遇到了一些问题。
- Your if statement didn't quite match your specification.
- To capture the output of the
xyzcommand, you should use$(xyz). - No need for stripping spaces from the output.
- If you don't want to pick up the
grepprocess as well (because it too has the pattern it's looking for), you should use the[firstchar]restgrep pattern (or you can use| grep sms_queue | grep -v grepto remove thegrepprocess from the count as well. - no need to use the string"15" in the comparison.
- 您的 if 语句与您的规范不太匹配。
- 要捕获
xyz命令的输出,您应该使用$(xyz). - 无需从输出中去除空格。
- 如果您也不想获取
grep进程(因为它也有它正在寻找的模式),则应该使用[firstchar]restgrep 模式(或者您也可以使用从计数中| grep sms_queue | grep -v grep删除该grep进程。 - 无需在比较中使用字符串“15”。
回答by MForster
If you want to copy the output of a command into a variable use this syntax:
如果要将命令的输出复制到变量中,请使用以下语法:
variable=$(my command)
回答by Roman Cheplyaka
How about
怎么样
pgrep -c sms_queue
?
?
And the whole (portable) version of the script would look like this:
整个(便携)版本的脚本如下所示:
if [ "$(pgrep -c sms_queue)" -le 15 ]; then
echo "Done."
else
echo "Not Complete."
fi

