【问题标题】:Not equals is not working as expected in shell scripting不等于在 shell 脚本中没有按预期工作
【发布时间】:2019-07-02 04:50:27
【问题描述】:

我正在尝试编写一个 shell 脚本来杀死一个进程,如果它已经存在于 jenkins 中并运行一个 jar。

我不确定哪里出错了。我通常想检查 processID 是否不为空,然后终止进程,否则打印 processID 不存在。

我浏览了下面的一些链接,他们建议使用“-z”来检查 null。因为我想检查 not null ,所以我使用了 [! -z $my_var] 但这似乎不起作用。

https://www.cyberciti.biz/faq/bash-shell-find-out-if-a-variable-has-null-value-or-not/

在 jenkins 中,执行 shell 代码:

            BUILD_ID=do_not_kill_me
            my_var=$(pgrep -f customer);
            if [[! -z $my_var]]
            then
                kill -9 "$my_var";
                echo "PID exists and killing it";   
            else
                echo "PID is null/PID doesn't exist";
            fi
            cp -rf customer*.jar /data/dev/customer/customer.jar
            java -jar /data/dev/customer/customer.jar &
            exit

我希望执行“If”部分中的数据,但总是执行 else。

当我点击 build now 时 jenkins 的示例输出,

        + BUILD_ID=do_not_kill_me
        + pgrep -f customer
        + my_var=15531
        + [[! -z 15531]]
        /tmp/jenkins390846207133389320.sh: 4: /tmp/jenkins390846207133389320.sh: [[!: not found
        + echo PID is null/PID doesn't exist
        PID is null/PID doesn't exist
        + cp -rf customer-management-0.0.1-SNAPSHOT.jar /data/dev/customer/customer.jar
        + exit

虽然我的 PID 存在,但它会返回打印消息,说明不存在。 让我知道哪里出错了

【问题讨论】:

    标签: bash shell jenkins


    【解决方案1】:

    以防万一,尝试添加空格:

     if [ ! -z ${my_var} ]
    

    您可以看到examples herehere

    【讨论】:

    • 空间是问题所在。非常感谢@VonC​​pan>
    • @Vignesh_A :在您的原始代码中,您使用了[[ ]],而不是[ ]。但是[[! 应该发出错误消息bash: [[!: command not found,除非您的路径中有一个有趣的名称为[[! 的可执行文件。由于您的脚本显示您没有收到错误消息,因此我建议您在 PATH 中搜索此类文件并将其删除,以避免将来出现问题。
    猜你喜欢
    • 2014-05-07
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2012-05-10
    • 2022-12-17
    • 2015-06-23
    相关资源
    最近更新 更多