簡體   English   中英

Bash腳本,具有基於模式運行的基本if / else和進程計數

[英]Bash script with basic if/else and count of processes running based on a pattern

我正在嘗試編寫一個腳本來計算與patern匹配的進程數。 如果它超過硬編碼值,那么做一些事情......否則做其他事情。

我發現使用的進程數:

ps ax | grep process_name | wc -l | sed -e "s: ::g"

如果上述命令的輸出大於15,則應該回顯“完成”。 否則,回顯“未完成”。

到目前為止,我有這個,但它沒有工作:

numprocesses=ps ax | grep sms_queue | wc -l | sed -e "s: ::g"
if [ $numprocesses -le "15" ] ; then
  echo "Done."
else
  echo "Not Complete."
fi
numprocesses=$(ps ax | grep '[s]ms_queue' | wc -l)
if [[ $numprocesses -gt 15 ]] ; then
  echo "Done."
else
  echo "Not Complete."
fi

你有一些問題。

  • 您的if語句與您的規范不完全匹配。
  • 要捕獲xyz命令的輸出,您應該使用$(xyz)
  • 無需從輸出中剝離空格。
  • 如果你也不想拿起grep進程(因為它也有它正在尋找的模式),你應該使用[firstchar]rest grep模式(或者你可以使用| grep sms_queue | grep -v grep來從計數中刪除grep進程。
  • 在比較中不需要使用字符串 “15”。

如果要將命令的輸出復制到變量中,請使用以下語法:

variable=$(my command)

怎么樣

pgrep -c sms_queue

整個(可移植)版本的腳本將如下所示:

if [ "$(pgrep -c sms_queue)" -le 15 ]; then
  echo "Done."
else
  echo "Not Complete."
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM