aboutsummaryrefslogtreecommitdiff
path: root/functions/utilities.zsh
diff options
context:
space:
mode:
authorDominik Ritter <dritter03@googlemail.com>2019-02-03 21:20:14 +0300
committerDominik Ritter <dritter03@googlemail.com>2019-02-03 21:20:14 +0300
commit40e04e053cae8b49b5b82c047660369f962d1975 (patch)
treec66bf2e5c13cd91592169a1e679631fc13a394bd /functions/utilities.zsh
parent747b94b1b6b8450375a2b1619d8a5c7336be1852 (diff)
Parse IPs properly
This is done if we want to show a public IP, internal IP, or a VPN. In the VPN case, what we actually want is to display an indicator that a VPN is active, instead of the VPN IP itself. We parse the IP here anyway, because we want to save some specific code there.
Diffstat (limited to 'functions/utilities.zsh')
-rwxr-xr-xfunctions/utilities.zsh48
1 files changed, 48 insertions, 0 deletions
diff --git a/functions/utilities.zsh b/functions/utilities.zsh
index 127007fb..a15bf650 100755
--- a/functions/utilities.zsh
+++ b/functions/utilities.zsh
@@ -371,3 +371,51 @@ function upsearch () {
popd > /dev/null
fi
}
+
+# Parse IP address from ifconfig on OSX and from IP on Linux
+# Parameters:
+# $1 - string The desired Interface
+# $2 - string A root prefix for testing purposes
+function p9k::parseIp() {
+ local desiredInterface="${1}"
+
+ if [[ -z "${desiredInterface}" ]]; then
+ desiredInterface="^[^ ]+"
+ fi
+
+ local ROOT_PREFIX="${2}"
+ if [[ "$OS" == "OSX" ]]; then
+ # Get a plain list of all interfaces
+ local rawInterfaces="$(${ROOT_PREFIX}/sbin/ifconfig -l 2>/dev/null)"
+ # Parse into array (split by whitespace)
+ local -a interfaces
+ interfaces=(${=rawInterfaces})
+ # Parse only relevant interface names
+ local pattern="${desiredInterface}[^ ]?"
+ local -a relevantInterfaces
+ for rawInterface in $interfaces; do
+ [[ "$rawInterface" =~ $pattern ]] && relevantInterfaces+=( $MATCH )
+ done
+ local newline=$'\n'
+ for interfaceName in $relevantInterfaces; do
+ local interface="$(${ROOT_PREFIX}/sbin/ifconfig $interfaceName 2>/dev/null)"
+ # Check if interface is UP.
+ if [[ "${interface/${newline}/}" =~ "<UP(,)?[^>]*>(.*?)inet[ ]*([^ ]*)" ]]; then
+ echo "${match[3]}"
+ return 0
+ fi
+ done
+ else
+ local -a interfaces
+ interfaces=( "${(f)$(${ROOT_PREFIX}/sbin/ip -brief -4 a show 2>/dev/null)}" )
+ local pattern="^${desiredInterface}[ ]+UP[ ]+([^/ ]+)"
+ for interface in "${(@)interfaces}"; do
+ if [[ "$interface" =~ $pattern ]]; then
+ echo "${match[1]}"
+ return 0
+ fi
+ done
+ fi
+
+ return 1
+}