运行shell脚本时找不到错误

时间:2013-02-04 10:30:30

标签: shell

我已经编写了一个shell脚本,如下所示

unicorn_cnt=$(ps -ef | grep -v grep | grep -c unicorn)
if (( $unicorn_cnt == 0 )); then
 echo "Unicorn Stopped" | mail -s "Alert - Unicorn" someone@somedomin.com
fi
delayed_job_cnt=$(ps -ef | grep -v grep | grep -c delayed_job)
if (( $delayed_job_cnt == 0 )); then
 echo "Delayed Job Stopped" | mail -s "Alert - Unicorn" someone@somedomin.com
fi
rake_cnt=$(ps -ef | grep -v grep | grep -c rake)
if (( $rake_cnt == 0 )); then
  echo "Convertion Stopped" | mail -s "Alert - Unicorn" someone@somedomin.com
fi

这是用于检查,是进程正在运行,如果没有发送警报邮件。我对shell脚本不是很熟悉。运行时显示以下错误。

process.sh: 3: process.sh: 2: not found
process.sh: 7: process.sh: 0: not found
process.sh: 11: process.sh: 0: not found

从某些研究我部分理解,这是因为创建变量时的空间问题。不确定。我尝试使用一些解决方案,如 sed 读取。但它仍显示错误。任何人都可以帮助我。

由于 此致

3 个答案:

答案 0 :(得分:1)

使用括号:

if [ "$unicorn_cnt" == 0 ]; then

或者更好地写这样:

if ! ps -ef | grep -q [u]nicorn; then
 echo "Unicorn Stopped" | mail -s "Alert - Unicorn" someone@somedomin.com
fi

这意味着'检查独角兽的ps -ef,如果找不到,请执行此操作'

答案 1 :(得分:0)

对于数字比较,您应使用eq而不是==。 使用[[作为条件表达式。 在邮件命令中使用here string而不是echo

试试这个:

if [[ $unicorn_cnt -eq 0 ]]; then
    mail -s "Alert - Unicorn" someone@somedomin.com <<< "Unicorn Stopped"
fi

答案 2 :(得分:0)

从上面的提示我找到了答案。

unicorn_cnt=$(ps -ef | grep -v grep | grep -c unicorn)
if [ $unicorn_cnt -eq 0 ]; 
then
  echo "Unicorn Stopped" | mail -s "Alert - Unicorn" someone@somedomin.com
fi
delayed_job_cnt=$(ps -ef | grep -v grep | grep -c delayed_job)
if [ $delayed_job_cnt -eq 0 ]; 
then
  echo "Delayed Job Stopped" | mail -s "Alert - Delayed Job" someone@somedomin.com
fi
rake_cnt=$(ps -ef | grep -v grep | grep -c rake)
if [ $rake_cnt -eq 0 ]; 
then
  echo "Convertion Stopped" | mail -s "Alert - Convertion" someone@somedomin.com
fi

它现在工作正常,我们也可以将它与cronjob集成。

相关问题