2

I'm trying to create an alias that starts with a pipe.

ex:

echo -i "hello\nworld" | grep world
> world
alias gr="| grep"
echo -i "hello\nworld" gr world
> hello
> world gr world

I.e, if the alias start with a pipe, aliasing doesn't seem to work properly. Is there a way to do this?

1
  • 2
    You can do this in zsh with a "global alias" but get to keep all the pieces when things break.
    – thrig
    Commented Aug 9, 2016 at 21:38

3 Answers 3

5

From man bash:

Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.

Pipe can't be the first word of a simple command.

6
  • 1
    Is there a mechanism like alias but more powerful to get this sort of functionality? Commented Aug 10, 2016 at 14:43
  • Nothing that doesn't involve more typing than you are trying to avoid (namely, using eval to execute a dynamically constructed command line).
    – chepner
    Commented Aug 11, 2016 at 0:48
  • @LeoUfimtsev, you can use zsh, then, for example, gp expands to | grep -i cheatsheet Commented Jan 20, 2019 at 11:53
  • @joeybaruch thanks for tip. Although I work as a consultant and often work in plain bash environments where I can't install custom packages like zsh, so was looking more of a pure bash kinda thing. Commented Jan 23, 2019 at 15:39
  • @LeoUfimtsev, I have a similar issue with remote servers I often log into. If you do find a workaround, please do update the solution. Commented Jan 29, 2019 at 19:03
2

Oh, your alias works. Try gr alone and your shell will throw syntax error because of | at the beginning of the line. That clearly means the alias works, i.e. it substitutes one string for another when it is supposed to.

In your example gr is treated as an argument to echo, that's why there is no substitution. It wouldn't be, even if there was no pipe inside the alias. The initial pipe symbol doesn't decide whether aliasing occurs or not; however it leads to an error when it does but this error has nothing to do with alias mechanics.

0

If you can/want to switch shell, you can do this in zsh, by setting the alias as

alias -g gr="| grep"

You must log in to answer this question.

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