2017-03-01 171 views
0

我不斷收到一元運算符。中國似乎沒有被賦予價值。這個Shell腳本有什麼問題?

PRC=`ps -ef | grep test | wc -l` 
if [ ${PRC} -eq 1 ] 
then 
    echo "Congrats" 
+2

那麼,您是否檢查過「PRC」的內容?另外,你應該在'[]':'[「$ prc」-eq 1]'中引用它。 –

+0

如果我運行這個'echo PRC ='ps -ef | grep test | wc -l'我得到PRC = 1,第一行拋出一個錯誤,如命令沒有找到 – vimal

回答

2

請注意,ps -ef | grep test通常會在輸出中包含grep進程,您可能不想這樣做。 A「巧招」,以避免這就是匹配的字符串「測試」使用正則表達式這不是簡單的字符串「測試」

$ ps -ef | grep test 
jackman 27787 24572 0 09:53 pts/2 00:00:00 grep --color=auto test 
$ ps -ef | grep test | wc -l 
1 

$ ps -ef | grep '[t]est' 
(no output) 
$ ps -ef | grep '[t]est' | wc -l 
0 

我做這往往不夠,我寫了這個bash函數psg(即 「PS的grep」):

psg() { 
    local -a patterns=() 
    (($# == 0)) && set -- $USER  # no arguments? vanity search 
    for arg do 
     patterns+=("-e" "[${arg:0:1}]${arg:1}") 
    done 
    ps -ef | grep "${patterns[@]}" 
} 

您也可以使用

pgrep -f test 
+0

偉大的思想認爲一樣! +1用於使用經常使用的功能的功能。 –

2

不要忘記你的收盤"fi"

PRC=`ps -ef | grep test| wc -l` 
if [ "${PRC}" -eq 1 ] 
then 
    echo "Congrats" 
fi 

你沒有提到什麼shell,但是這個工作在bash。

保存使用-c​​過程(計數)的選項給grep:

PRC=`ps -ef | grep -c test` 

被告知您的管道都包括在計數grep命令本身,所以當你在你的評論中提及上面的計數最有可能誤導,因爲它只是在自我計數。相反,使用這樣的:

PRC=`ps -ef | grep -c [t]est` 

這將匹配與他們「測試」,而不是grep命令本身的命令。這是因爲這是使用正則表達式匹配以「t」開頭的單詞。你的命令以方括號開始,所以它不會匹配它自己。抵制做一個「grep測試| grep -v grep」,這是馬虎,只是不必要地使用一個進程。