使用shell脚本检查进程是否正在运行

时间:2016-07-08 21:56:44

标签: bash shell unix

我正在尝试创建一个脚本来查看进程chrome是否正在运行。 如果进程正在运行,脚本应每10秒检查一次,并且当它找到10次时必须结束。 这是我的代码。

#!/bin/bash

count=0

while true; do
    sleep 10s
    isthere=`$(top) | grep -w chromium`
    if [ $isthere -ne 0 ]; then
        count=$((count+1))
    fi
    if [ $count -eq 10 ]; then
        echo "You found the process 10 times"
        exit 50
    fi
done

我没有任何输出。我不知道我是否正确使用命令top

2 个答案:

答案 0 :(得分:1)

请使用<a title='Upload file' href='#!' id=$row[questionID] class='btn btn-default btn-xs upload_files'> <input name="4117" value="1983" id="option_1983" type="radio"> <input name="4117" value="1984" id="option_1984" type="radio">

pgrep

循环:

$ if pgrep ksh >/dev/null; then echo "ksh is running"; fi
ksh is running

使用您选择的工具替换i=0 while (( i < 10 )); do if pgrep ksh >/dev/null; then (( ++i )) fi sleep 10 done

答案 1 :(得分:1)

是的,您对top命令的使用不正确。您尝试从shell脚本调用它并因此挂起。

您应该使用top命令和一些特定选项。我建议你使用-b选项,它对应于&#34;批次&#34;模式和-n选项用于迭代次数top生成其输出。有关详细信息,请查看man top

还应该修改isthere变量的测试(我们检查它是否为非空)。

生成的脚本是这样的:

#!/bin/bash

count=0

while true; do
    sleep 10s
    isthere=`top -b -n 1 | grep -w chromium`
    if [ -n $isthere ]; then
        count=$((count+1))
    fi
    if [ $count -eq 10 ]; then
        echo "You found the process 10 times"
        exit 50
    fi
done
相关问题