Search code examples
bashsshio-redirectionstderr

awk returns two different outputs for the same input


I'm trying to get first field value using awk field separator, but it is failing as below. Same is working fine when i'm trying with echo manually.

Fail Case 1:

[root@centos ~]# ssh -V | awk -F_ '{print $1}'

Output: OpenSSH_8.7p1, OpenSSL 3.0.7 1 Nov 2022

Fail Case 2:

[root@centos ~]# ssh -V | awk 'BEGIN{FS="_"} {print $1}'

Output: OpenSSH_8.7p1, OpenSSL 3.0.7 1 Nov 2022

Working Case with "echo"

[root@centos ~]# echo "OpenSSH_8.7p1, OpenSSL 3.0.7 1 Nov 2022" | awk -F_ '{print $1}'

Output:  OpenSSH

I found a similar problem here but it's not working in my case. What is it i'm failing to understand here?


Solution

  • ssh -V is writing its output to stderr, not stdout, so what you are seeing printed is the error stream that didn't go through awk at all.

    An easy fix: redirect stderr to stdout.

    ssh -V 2>&1 | awk -F_ '{print $1}'