【问题标题】:Error in checking string is null in shell script?在 shell 脚本中检查字符串是否为空时出错?
【发布时间】:2016-05-15 01:02:07
【问题描述】:
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 ] 选项。但两者都给出错误。

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

【问题讨论】:

    标签: android shell unix android-shell


    【解决方案1】:

    检查空字符串。

    例子:

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

    【讨论】:

      【解决方案2】:

      要检查一个空字符串,你需要使用-z。

      例子:

      if [ -z "$str" ] ;
      

      【讨论】:

      • 我也认为“pidString=$(ps | grep ${pid})”语句不正确。您是否尝试检查 pid 是否处于活动状态?
      猜你喜欢
      • 2012-11-10
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2015-06-12
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多