Arch Linux Shell Scripts: Bash return local IP

This post is a note in case I have to rewrite the .bashrc on system crash or some such potential catastrophe. In order to facilitate shell based configuration, it is helpful to have .bashrc display the local and public IP address (IPv4). To that end a simple shell script can be added to .bashrc creating the desired outcome.

Local IP Address

The following ip command will display the local IP address only:

ip address | grep "inet 192." | grep -o -E "[0-9]{3}\.[0-9]{3}\.[0-9]{1}\.[0-9]{3}\/" | grep -o -E "[0-9]{3}\.[0-9]{3}\.[0-9]{1}\.[0-9]{3}"

There is probably a better way to do it and if you have any suggestions feel free to comment.

Public IP Address

The following command will display the public ip address:

curl ipinfo.io/ip

References:

  1. https://www.reddit.com/r/kde/comments/kfqqui/konsole_default_profile/ – Set default profile in Konsole
  2. https://www.google.com/search?q=bash+echo+with+no+newline&oq=bash+echo+with+no+newline&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQLhhA0gEINjYzMWowajGoAgCwAgA&sourceid=chrome&ie=UTF-8 – echo with no \n
  3. https://www.google.com/search?q=grep+show+only+first+match+in+line&oq=grep+show+only+first+match+in+line&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQLhhA0gEINDE5OWowajSoAgCwAgA&sourceid=chrome&ie=UTF-8 – grep only first match
  4. https://www.unix.com/shell-programming-and-scripting/234273-regex-match-only-first-occurence-grep.html – Use regex to filter out just the local IP address
  5. https://stackoverflow.com/questions/14594151/methods-to-detect-public-ip-address-in-bash – display public id address in bash

Leave a Reply

Your email address will not be published. Required fields are marked *