Skip to content

Bash variable in an awk search pattern

wordpress meta

title: 'Bash variable in an awk search pattern'
date: '2017-10-20T15:15:44-05:00'
status: publish
permalink: /bash-variable-in-an-awk-search-pattern
author: admin
excerpt: ''
type: post
id: 1146
category:
    - awk
    - RDP
    - SSH
tag: []
post_format: []

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
10.1.4.4

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
     HostName 10.1.4.4
$ awk "/^Host $host$/{x=1}x&&/HostName/{print $2;exit}" ~/.ssh/Prod-config
     HostName 10.1.4.4

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
10.1.4.4

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
     HostName 10.1.4.4
     ProxyJump gw01

$ cat rdesktop_jumphost.sh 
#!/bin/bash
host=$1
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)
localRdpPort=33389

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