Bash IF 语句 : string comparison of command output always false

标签 bash if-statement gnu-screen

您好,我正在尝试编写一个简单的 bash 脚本来附加到 screen session 。如果 session 尚未启动,那么它将启动它并尝试再次附加。

我遇到的问题是 if 语句;它应该将 screen 命令的输出与失败消息进行比较,如果它们相等,则继续启动 session 并附加。但它总是转到 else 子句,打印出我正在检查的错误消息 :s

两个字符串包含相同的东西:

"There is no screen to be attached matching sctest."

但是 bash 认为它们是不同的...

这是 bash 脚本,我错过了什么?

#!/bin/bash

screenOutput=$(screen -aA -x sctest);
failString="There is no screen to be attached matching sctest.";

if [ "$screenOutput" = "$failString" ]; then
    echo "screen session not started. starting now...";

    # . ./init.sh

    # echo $(screen -aA -x sctest);
else
    echo "$screenOutput";
fi

最佳答案

使用 set -x(或调用 bash -x yourscript)打印每一行,因为它是用使隐藏字符可见和人性化的方式扩展的值来评估的可读。

您很可能会看到如下内容:

[ 'There is no screen to be attached matching sctest' = $'There is no screen to be attached matching sctest\r' ]

...后者的末尾有一个 \r 。这是一个回车。

要删除它,您可以像这样修改代码:

screenOutput=$(screen -aA -x sctest)
screenOutput=${screenOutput%$'\r'}

关于Bash IF 语句 : string comparison of command output always false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35214648/

相关文章:

go - 在 Go 中作为命令启动 screen ?

linux - 在 bash 脚本中调用 SSH Sudo 命令

c++ - 双输入验证 C++ 程序的问题

python - python脚本失败时记录

bash - .profile 有调用.bashrc 的语句,但是.bashrc 没有执行

MySQL 查询 - IF 或 CASE 以及 AND 和异常(exception)(用于计算)

python - 将 "Ctrl-A"放入 Python shell 脚本中

linux - 如何使用 bash 检查字符串是否是有效的 mailq mailid?

arrays - Bash:嵌套for循环+中间循环包含两个数组?

c++ - 在管道中调用时从 std::cin 加载 pugi::xml_document 失败