Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search .netrc file in bash, and return username for given machine

Tags:

grep

bash

awk

I need a way (the most portable) in bash, to perform a search of the ~/.netrc file, for a particular machine api.mydomain.com and then on the next line, pull the username value.

The format is:

machine a.mydomain.com
  username foo
  passsword bar
machine api.mydomain.com
  username boo
  password far
machine b.mydomain.com
  username doo
  password car

So, it should matchin api.mydomain.com and return exactly boo from this example.

awk '/api.mydomain.com/{getline; print}' ~/.netrc

Get's me the line I want, but how do I find the username value?

like image 623
Justin Avatar asked Sep 16 '25 20:09

Justin


1 Answers

$ awk '/api.mydomain.com/{getline; print $2}' ~/.netrc
boo

To capture it in a variable:

$ name=$(awk '/api.mydomain.com/{getline; print $2}' ~/.netrc)
$ echo "$name"
boo

By default, awk splits records (lines) into fields based on whitespace. Thus, on the line username boo, username is assigned to field 1, denoted $1, and boo is assigned to field 2, denoted $2.

like image 166
John1024 Avatar answered Sep 19 '25 12:09

John1024