代码之家  ›  专栏  ›  技术社区  ›  Kyu96

Bash子字符串比较不适用于命令表达式

  •  0
  • Kyu96  · 技术社区  · 4 年前

    我试图在bash中比较一个子字符串( How to check if a string contains a substring in Bash ). 通常我可以这样做:

    if [[ "sdfdsfOpenSSHdsfsdf" == *"OpenSSH"* ]]; then echo "substring found"; fi
    

    但是,当使用交互式命令时,它不起作用:

    if [[ $(ssh -V) == *"OpenSSH"* ]]; then echo "substring found"; fi
    

    输出的 ssh -V OpenSSH_8.4p1, OpenSSL 1.1.1h 22 Sep 2020 ,所以我希望子字符串是匹配的。我错过了什么?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Chris Maes    4 年前

    输出 ssh -V 转到stderr,您需要重定向到 stdout 为了捕捉它:

    ssh -V 2>&1
    

    因此,以下工作:

    if [[ $(ssh -V 2>&1) == *"OpenSSH"* ]]; then echo "substring found"; fi