Ubuntu: How to set an Alias in bashrc so that System IP can be found using a simple alias command?


As seen from this question, the following command gives the IP address of the system. ip route get | awk '{print $NF; exit}'

I wanted to make use of this command to create an alias so that I do not have to type such a long command everytime. So, I added the following line into .bashrc

alias ipconfig="ip route get | awk '{print $NF; exit}'"  

But I am facing an issue with the awk command when I use it with the alias (specifically, I think the $NF variable is not set. I have provided three versions of the output using the commandline and the set alias for better understanding.

dennis@dennis-HP:~$ ip route get | awk '{print $NF; exit}'  192.168.0.X     dennis@dennis-HP:~$ ipconfig via 192.168.0.Y dev wlx9d5d8eae8f64  src 192.168.0.X    dennis@dennis-HP:~$ ip route get via 192.168.0.Y dev wlx9d5d8eae8f64  src 192.168.0.X       cache   

How can I get it to produce the same output?


The problem is that the (intended awk variable) $NF is being expanded by the shell at alias declaration time, not when called later. So, the alias is being eventually declared as:

alias ipconfig="ip route get | awk '{print}'"  

and this will print the whole record obviously.

You need to prevent the premature expansion by any usual escaping mechanism, here i'm using backslash -- \:

$ alias ipconfig="ip route get | awk '{print \$NF}'"    $ ipconfig  

Or if your feel advantageous, you can play with the ugly single quote hacks:

$ alias ipconfig='ip route get | awk '\''{print $NF}'\'''    $ ipconfig  

As a side note, you should only alias when making simple substitutions, for any complex cases, you should really look at leveraging functions, they are far more readable and reliable. For example, this one could simply take the following form (forget about quoting and other hacks):

$ ipconfig() { ip route get | awk '{print $NF}' ;}    $ ipconfig  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »