Quick Bash Tricks to Retrieve Server IP Addresses with awk, grep, and sed
Learn quick Bash commands and scripts to extract a server's IP address—using awk, grep, sed, or a custom shell script—to retrieve a single interface IP or list all network interfaces, complete with example outputs for typical Linux environments.
Here are several scripts to obtain the IP address of the local server using common Linux command-line tools.
Get IP using awk
# ifconfig ens33 | awk 'NR==2{print $2}'
192.168.154.5Get IP using grep
# ifconfig ens33 | egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n 1
192.168.154.5Get IP using sed
# ifconfig ens33 | sed -n '/inet /p' | sed 's/inet \([0-9.]\+\).*/\1/' | tr -d ' '
192.168.154.5Get all interface IPs
# cat ip.sh
#!/bin/bash
# Author: cn-Linuxer
ifs=(`ifconfig | grep "^e" | awk -F: '{print $1}'`)
for i in ${ifs[@]}; do
echo -e "${i}
\t`ifconfig ${i} | awk 'NR==2{print $2}'`"
done
# sh ip.sh
ens33
192.168.154.5
ens35
192.168.156.5Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
