본문으로 건너뛰기
0%
약 1분 (348 단어) ko

Quick & Dirty: Getting IP Address with Bash

Categories TechSavvy Bash
Tags #TechSavvy #ProgrammingLanguage #Bash

The Problem

Ever needed to grab your IP address from a bash script? Here’s a quick one-liner that’s saved me countless times!

The Solution

If your ethernet interface is eth0:

$ IPADDR=$(ifconfig eth0|grep inet|head -1|sed 's/\:/ /'|awk '{print $2}')
$ echo $IPADDR
172.17.0.3

How It Works

Let’s break this down step by step:

  1. ifconfig eth0 - Gets interface information for eth0
  2. grep inet - Filters for lines containing “inet”
  3. head -1 - Takes just the first match
  4. sed 's/\:/ /' - Replaces colons with spaces for easier parsing
  5. awk '{print $2}' - Grabs the second field (which is our IP)

Modern Alternative

If you’re on a newer system, you might prefer using ip instead of the older ifconfig:

$ IPADDR=$(ip route get 1 | awk '{print $NF;exit}')
$ echo $IPADDR
172.17.0.3

This approach is more reliable because it gets the IP of the interface that would be used to reach the internet.

Pro Tips

  • Always test your scripts in your specific environment - network interface names can vary!
  • For production scripts, add error checking to make sure the interface exists
  • Consider what happens if the interface is down or doesn’t have an IP

Appendix: References

Sometimes the simplest solutions are the best ones! 🚀

Share this article

Found this helpful? Share it with your network

Join the Discussion

Share your thoughts and connect with other readers

댓글

GitHub 계정으로 로그인하여 댓글을 남겨보세요. 건설적인 의견과 질문을 환영합니다!

댓글을 불러오는 중...