Bash alias with piping

8

1

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.

n8felton

Posted 2012-03-31T22:02:58.267

Reputation: 243

Answers

9

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

Try using "double quotes" in the inner expression.

slhck

Posted 2012-03-31T22:02:58.267

Reputation: 182 472

Or escaped single quotes. – Benjamin Bannier – 2012-03-31T22:16:55.753

Thank you soooo much. I knew it was something simple, I was just looking at it for too long. – n8felton – 2012-03-31T22:26:22.933

5

You cannot escape single quotes inside a single quoted string: http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

– glenn jackman – 2012-04-01T01:56:23.863

7

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
}

kakyo

Posted 2012-03-31T22:02:58.267

Reputation: 260

4What'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 – 2016-01-09T15:33:19.120

@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 – 2019-04-17T02:25:00.280