0

As seen from this question, the following command gives the IP address of the system. ip route get 8.8.8.8 | 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 8.8.8.8 | 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 8.8.8.8 | awk '{print $NF; exit}'
192.168.0.X 

dennis@dennis-HP:~$ ipconfig
8.8.8.8 via 192.168.0.Y dev wlx9d5d8eae8f64  src 192.168.0.X

dennis@dennis-HP:~$ ip route get 8.8.8.8
8.8.8.8 via 192.168.0.Y dev wlx9d5d8eae8f64  src 192.168.0.X 
    cache 

How can I get it to produce the same output?

2
  • do you have a question? what are you trying to accomplish?
    – Skaperen
    Jul 25, 2017 at 5:07
  • I have modified the question. Please remove the downvote Jul 25, 2017 at 5:09

1 Answer 1

5

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 8.8.8.8 | 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 8.8.8.8 | awk '{print \$NF}'"

$ ipconfig
192.168.2.6

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

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

$ ipconfig
192.168.2.6

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 8.8.8.8 | awk '{print $NF}' ;}

$ ipconfig
192.168.2.6

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .