I am making some aliases for my terminal to output different IP addresses. Two out of three of them work just fine, but my one for default gateway won't return a clean response.

alias inet="hostname -I | awk '{print $3}'" 

returns: 192.168.xxx.xx as intended

alias pubip="curl ifconfig.me"

returns: 354.xxx.xx.xx as intended

However the alias I made to return the default gateway ip

alias def="ip r | grep default | awk '{print $3}'"

returns : default via 192.168.xxx.xxx dev eth0

I use the same line in the terminal and it will return just the default gateway as intended.

But when it is stored as an alias the "awk" portion of the script doesnt work.

Can I not pipe twice in an alias? Is there something else wrong in my code?


In your alias definition, $3 is actually expanded at the moment the alias is defined (although it doesn't look so at the first glance). If you type alias after defining your alias (to view defined aliases), you will see that your alias actually has the form

alias def='ip r | grep default | awk '\''{print }'\'''

and because of print alone in awk, the entire line returned by grep is printed.

Use the following to define the alias:

alias def="ip r | grep default | awk '{print \$3}'"

Then your alias will have the form:

alias def='ip r | grep default | awk '\''{print $3}'\'''

and it will work as you want.

  • You are very greatly appreciated. The full explanation was great, I wasn't sure if i needed to escape some character or what, but yes it now works as intended. You have a good day Sep 27 at 19:51
  • 5
    you can also eliminate the grep: alias def="ip r | awk '/default/ {print \$3}'"
    – mpez0
    Sep 28 at 13:48
  • 4
    You could also define a function instead of alias, and not have to worry about any of this.
    – Barmar
    Sep 28 at 15:02
  • 1
    If just getting the output is a goal (and not using awk), then you can use the simple cut command like so: alias def="ip r|grep default|cut -d\" \" -f3". The -d defines a "space" as the delimiter and the -f specifies the field to print. The backslashes are needed because we are wrapping the command in an alias which already has quotes at the beginning and end. If we print the command in the terminal, they are not needed. Oct 1 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.