2016-02-05 86 views
0
I am new to Shell Scripts and not aware of the syntax. 

我有我推到我的Android設備,然後用「busybox的DOS2UNIX的」轉換成爲一個shell腳本:在shell腳本中檢查字符串錯誤是否爲空?

adb shell busybox dos2unix /data/local/myShellScript.sh 

在劇本我想檢查一個字符串是否爲空或不 ? 但我得到錯誤:'意外的操作符/操作數'。

下面是我的代碼:

echo "Getting a PID (Process ID) from a file" ; 
pid=`cat /sdcard/PIDofTask.txt` ; 
echo "PID of task is : " $pid ; 
echo "Checking if the pid exists, to verify the process is running" ;  
pidString=$(ps | grep ${pid}) ; 
echo "PID string : " $pidString ; 

if [ $pidString ] ; 
then 
    echo "pid String is not empty" ; 
else 
    echo "pid String is empty" ; 
fi ; 

輸出:

Getting a PID (Process ID) from a file 
PID of task is : 11571 
Checking if the pid exists, to verify the process is running 
PID string : root 11571 8082 4180 1828 poll_sched 7faa42dcdc S sh 
/data/local/myShellScript.sh[2]: [: 11571: unexpected operator/operand 
pid String is empty 

我也曾嘗試[-n $ pidString]也[-z $ pidString]選項。但是兩者都給出了錯誤。

我在哪裏做錯了? 真的很感謝幫助...

回答

1

要檢查一個空字符串,你需要使用-z。

實施例:

if [ -z "$str" ] ; 
+0

也是我認爲聲明 「pidString = $(PS | grep的$ {} PID)」 是不正確。你是否試圖檢查pid是否激活? –

1

要檢查空字符串。

例子:

line="hello welcome" 
if [ -z "$line" ] ; then 
echo "String null" 
fi 
+0

工作。如此愚蠢的我,缺少雙引號!謝謝您的幫助 – gambit

相關問題