1. 程式人生 > 其它 >分享一個shell指令碼的坑:grep匹配+wc取值 在指令碼執行後的結果與手動執行結果不一致

分享一個shell指令碼的坑:grep匹配+wc取值 在指令碼執行後的結果與手動執行結果不一致

技術標籤:Linux

文章目錄

場景

[[email protected] test]$ ll
total 4
-rw-r--r--. 1 admin admin    0 Dec 10 16:44 app.jar
-rwxr-xr-x. 1 admin admin 1604 Dec 10 16:42 app.sh

shell 指令碼部分內容如下

function status()
{
    #count=`ps -ef |grep app|grep -v $0|grep -v grep|wc -l`
    count=`ps
-ef |grep app|grep -v grep|wc -l`
echo "____________________$count" if [ $count != 0 ];then echo "alert is running..." else echo "alert is not running..." fi }

問題復現

手動執行

[[email protected] test]$ ps -ef |grep alert |grep -v grep|wc -l
0

指令碼執行

[[email protected] test]$ ./app.sh status
____________________2
app is running...
[[email protected] test]$ sh app.sh status
____________________2
app is running...

發現指令碼執行過程中,看到賦予count引數的結果值是2!但是手動執行ps -ef|grep app|grep -v grep|wc -l的結果明明是0!!

分析原因

指令碼名稱與app應用名稱一致導致 count 統計不準確 需要將指令碼名稱排除在外

count=ps -ef |grep app|grep -v $0|grep -v grep|wc -l

解決方案

第一種:修改app.sh 名稱 test.sh
第二種:修改指令碼內容如下

count=`ps -ef |grep app|grep -v $0|grep -v grep|wc -l`

count=`ps -ef |grep app.jar|grep -v $0|grep -v grep|wc -l`