Warm tip: This article is reproduced from serverfault.com, please click

Bash substring comparison doesn't work for command expression

发布于 2020-12-02 08:30:57

I am trying to compare a substring in bash (How to check if a string contains a substring in Bash). Normally I can do this like so:

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

However, when using an interactive command it doesn't work:

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

The output of ssh -V is OpenSSH_8.4p1, OpenSSL 1.1.1h 22 Sep 2020, so I would expect the substring to be matched. What am I missing?

Questioner
Kyu96
Viewed
0
Chris Maes 2020-12-02 16:33:55

the output of ssh -V goes to stderr, you need to redirect to stdout in order to capture it:

ssh -V 2>&1

so the following works:

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