2012-01-04 121 views
1

我有以下shell腳本:條件shell腳本

#!/bin/sh 
output=`./process_test.sh status_pid | grep "NOT STARTED: process_1" --line-buffered` 
if[[ -z ${output} ]] 
then 
    echo "process is not running" 
else 
    echo "process is running" 
fi 

其中./process_test.sh status_pid是我查找進程是否正在運行或不.e.g效用。如果process_1未運行,則將顯示:NOT STARTED: process_1。進一步 這個工具是完美的,沒有任何問題。我懷疑問題是與if語法

上運行該腳本,我得到以下的輸出:

./test.sh: line 18: if[[ -z NOT: command not found 
./test.sh: line 19: syntax error near unexpected token `then' 
./test.sh: line 19: `then' 

你能幫助解決這個問題?

回答

3

必須使用空格來分隔關鍵字,例如if與參數或命令(如[[)。

#!/bin/sh 
output=$(./process_test.sh status_pid | grep -e "NOT STARTED: process_1" --line-buffered) 
if [[ -z ${output} ]] 
then 
    echo "process is not running" 
else 
    echo "process is running" 
fi 
+0

你用問題和答案的編輯來擊敗我。 :)速度+1 ... – 2012-01-04 08:08:19

1

你應該把它寫像

if [[ -z ${output} ]] 
then 
    ... 

所以,你已經錯過了

0

這將是一個更加簡潔寫這篇文章:

 
#!/bin/sh 
if ! ./process_test.sh status_pid | 
     grep "NOT STARTED: process_1" > /dev/null; then 
    echo "process is not running" 
else 
    echo "process is running" 
fi 

注意,--line緩衝的說法是無關緊要的,因爲 管道是不會結束直到所有輸入的 是讀。 (嗯,這並不完全不相關 - 它會使 腳本運行速度慢得可以忽略不計。)

另請注意'[['不是標準的。根據shell language specification,其 「可能被識別爲(a)在某些實施方式上保留(單詞)...,導致未指定的結果」。換句話說,它就是通常所說的「bashism」(雖然它在bash以外的shell中是有效的),並且如果使用它,則不得使用#!/bin/sh作爲解釋器,但應指定#!/bin/bash