Score:8

Why does this alias using awk not return a clean response like my other two?

cn flag

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?

Score:15
cn flag
raj

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.

JakobyScream avatar
cn flag
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
us flag
you can also eliminate the grep: `alias def="ip r | awk '/default/ {print \$3}'"`
cn flag
You could also define a function instead of alias, and not have to worry about any of this.
Hopping Bunny avatar
cn flag
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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.