Bash Script to Find IP Address Easily
ip addr show | grep 'inet ' | awk '{print $2}' | cut -d/ -f1 to find your IP address in a script.Examples
How to Think About It
Algorithm
Code
#!/bin/bash ip addr show | grep 'inet ' | awk '{print $2}' | cut -d/ -f1
Dry Run
Let's trace the command on a machine with IP 192.168.1.10
List interfaces
ip addr show outputs lines including 'inet 192.168.1.10/24'
Filter inet lines
grep 'inet ' keeps lines with IP addresses like 'inet 192.168.1.10/24'
Extract IP
awk '{print $2}' gets '192.168.1.10/24', cut -d/ -f1 trims to '192.168.1.10'
| Command Step |
|---|
| ip addr show |
| grep 'inet ' |
| awk '{print $2}' |
| cut -d/ -f1 |
Why This Works
Step 1: Get network info
The ip addr show command lists all network interfaces and their details including IP addresses.
Step 2: Filter IP lines
Using grep 'inet ' selects only lines that contain IPv4 addresses.
Step 3: Extract IP address
The awk '{print $2}' command picks the second word which is the IP with subnet, and cut -d/ -f1 removes the subnet mask, leaving just the IP.
Alternative Approaches
hostname -I | awk '{print $1}'ifconfig | grep 'inet ' | awk '{print $2}'
ip -j addr show | jq -r '.[].addr_info[] | select(.family=="inet") | .local'Complexity: O(n) time, O(1) space
Time Complexity
The commands process each line of the network info once, so time grows linearly with the number of interfaces.
Space Complexity
The script uses minimal extra memory, only storing small parts of the output at a time.
Which Approach is Fastest?
Using hostname -I is fastest and simplest but less flexible; parsing ip addr show is more robust for detailed info.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ip addr show + grep + awk + cut | O(n) | O(1) | Detailed and reliable IP extraction |
| hostname -I | O(1) | O(1) | Quick and simple IP list |
| ifconfig + grep + awk | O(n) | O(1) | Legacy systems compatibility |
| ip -j addr show + jq | O(n) | O(n) | Structured JSON output, needs jq |
hostname -I for a quick way to get all IP addresses in one line.