Operations 3 min read

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.

Open Source Linux
Open Source Linux
Open Source Linux
Quick Bash Tricks to Retrieve Server IP Addresses with awk, grep, and sed

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.5

Get IP using grep

# ifconfig ens33 | egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n 1
192.168.154.5

Get IP using sed

# ifconfig ens33 | sed -n '/inet /p' | sed 's/inet \([0-9.]\+\).*/\1/' | tr -d ' '
192.168.154.5

Get 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.5
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

bashgrepIP addressawksedshell-script
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.