Quick & Dirty: Getting IP Address with 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:
ifconfig eth0
- Gets interface information for eth0grep inet
- Filters for lines containing “inet”head -1
- Takes just the first matchsed 's/\:/ /'
- Replaces colons with spaces for easier parsingawk '{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
- General Bash Guide: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Sometimes the simplest solutions are the best ones! 🚀
Share this article
Found this helpful? Share it with your network
관련 글
Working with Bash Arrays
Bash: How to Check if Directory Exists
Bash eval - Dynamic Command Execution
Join the Discussion
Share your thoughts and connect with other readers
댓글
GitHub 계정으로 로그인하여 댓글을 남겨보세요. 건설적인 의견과 질문을 환영합니다!
댓글을 불러오는 중...
댓글을 불러올 수 없습니다.