Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!


Bash variable in an awk search pattern

I spent some time getting this working so documenting for reference.

Trying to grab an IP address from a ssh config file works fine using a static string.

$ awk '/^Host rdpclient1$/{x=1}x&&/HostName/{print $2;exit}' ~/.ssh/Prod-config

Using double quotes and a static variable or double quotes and a bash variable does not work.

$ awk "/^Host rdpclient1$/{x=1}x&&/HostName/{print $2;exit}" ~/.ssh/Prod-config
$ awk "/^Host $host$/{x=1}x&&/HostName/{print $2;exit}" ~/.ssh/Prod-config

Using double quotes plus a bash variable and escaping the print variable $2 works.

$ awk  "/^Host ${host}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config

And an in a little script that use ssh config settings for my RDP through a jumphost or bastion Linux server.

Host gw01
     HostName <public IP>
     User opc
     IdentityFile mysshkey
Host rdpclient1
     ProxyJump gw01

$ cat rdesktop_jumphost.sh 
privateIP=$(awk  "/^Host ${host}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config)
jumphost=$(awk "/^Host ${host}$/{x=1}x&&/ProxyJump/{print \$2;exit}" ~/.ssh/Prod-config)
jumphostIP=$(awk "/^Host ${jumphost}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config)
jumpuser=$(awk "/^Host ${host}$/{x=1}x&&/User/{print \$2;exit}" ~/.ssh/Prod-config)

ssh -f -N -p 22 -L $localRdpPort:$privateIP:3389 -i mysshkey $jumpuser@$jumphostIP
tunnelpid=$(ps -ef | grep $localRdpPort | grep -v grep | awk '{print $2}')

rdesktop localhost:$localRdpPort

kill $tunnelpid


Bio Info for Riaan