在shell脚本中检查字符串时出错是否为空?

时间:2016-02-05 06:27:30

标签: android shell unix android-shell

I am new to Shell Scripts and not aware of the syntax.

我有一个shell脚本,我正在推送到我的Android设备,然后转换为' busybox dos2unix' :

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]选项。但两者都有错误。

我在哪里犯了错误? 非常感谢帮助...

2 个答案:

答案 0 :(得分:2)

检查空字符串。

示例:

new String(kSecret, "UTF-8");

答案 1 :(得分:1)

要检查空字符串,您需要使用-z。

示例:

if [ -z "$str" ] ;