12

I'm not exactly sure what I'm doing wrong with this one. I'm trying to run the command

alias localip='ip -4 -o addr show eth0 | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | head -n 1'

If I run the command

ip -4 -o addr show eth0 | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | head -n 1

I get the result I expect, however, when trying to create an alias with the command, I get

-bash: syntax error near unexpected token `('

Any help would be appreciated. TIA.

2 Answers 2

11

You're nesting single quotes within single quotes. That doesn't work.

Try using "double quotes" in the inner expression.

3
8

I found it a much cleaner solution to just create a function and name your alias after the function, like this:

alias localip=GetLocalIP

function GetLocalIP()
{
   ip -4 -o addr show eth0 | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | head -n 1
}
4
  • 6
    What's the advantage of creating an alias to a function, rather than just naming the function localip? Also, the function keyword breaks compatibility with other shells. I'd suggest just using localip() { ...
    – Tom Fenech
    Jan 9, 2016 at 15:33
  • @TomFenech Your suggestion works in general. It's just a personal style that works for me: All my functions start with a verb, so that it makes sense in code (reused elsewhere). . However, that style slows me down when it comes to CLI typing. So alias comes as a compromise. Verbosity like the function keyword helps me define code parsers or generators later.
    – kakyo
    Apr 17, 2019 at 2:25
  • @tom-fenech - I'm going to poke around in some of the other shells I tend to use, but out of curiosity, what are some of the shells that are incompatible?
    – AFK
    Dec 26, 2021 at 6:34
  • 1
    @AFK see this question for a thorough discussion on that topic.
    – Tom Fenech
    Feb 8 at 12:37

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.