Created
January 25, 2021 16:08
-
-
Save tadpol/98eb76bc63b8c4bdecf623b08e0bc898 to your computer and use it in GitHub Desktop.
ZSH function to scan .netrc file for matching machine and login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scan_netrc { | |
local host_to_find=$1 | |
local user_to_find=$2 | |
local netrc=($(< ~/.netrc )) | |
# This does not correctly handle `macrodef` | |
# netrc is a series of key-value pairs seperated by anysort of white space. | |
# (netrc explictily does not handle password with whitespace in them) | |
# Strictly, netrc only mactches on `machine` and there can only be one of each. | |
local key='' | |
local state=START | |
local found_password='' | |
for i in $netrc | |
do | |
# echo "[k: $key s: $state] $i" | |
case $i in | |
machine) | |
key=machine | |
state=machine | |
;; | |
login) | |
key=login | |
;; | |
password) | |
key=password | |
;; | |
*) | |
if [[ $key = machine && "$i" = "$host_to_find" ]]; then | |
state=MACHINE_FOUND | |
fi | |
if [[ $state = MACHINE_FOUND* && $key = password ]]; then | |
found_password=$i | |
if [[ $state == MACHINE_FOUND_LOGIN ]]; then | |
echo $found_password | |
return 0 | |
else | |
state=MACHINE_FOUND_PASSWORD | |
fi | |
fi | |
if [[ $state = MACHINE_FOUND* && $key = login && "$i" = "$user_to_find" ]]; then | |
if [[ $state == MACHINE_FOUND_PASSWORD ]]; then | |
echo $found_password | |
return 0 | |
else | |
state=MACHINE_FOUND_LOGIN | |
fi | |
fi | |
;; | |
esac | |
done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment