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


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?

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

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.

  • 1
    Is there a mechanism like alias but more powerful to get this sort of functionality? – Leo Ufimtsev Aug 10 '16 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 Aug 11 '16 at 0:48
  • @LeoUfimtsev, you can use zsh, then, for example, gp expands to | grep -i cheatsheet – Joey Baruch Jan 20 '19 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. – Leo Ufimtsev Jan 23 '19 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. – Joey Baruch Jan 29 '19 at 19:03

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.


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

alias -g gr="| grep"

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.