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


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

我有一个 shell 脚本,我正在推送到我的安卓设备,然后用"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 ] 选项。但两者都给出了错误。

我哪里做错了?非常感谢帮助...

检查空字符串。

例:

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

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

例:

if [ -z "$str" ] ;

最新更新