This article was published on July 6th 2014 and takes about 2 minutes to read.
Use it with caution — it is probably still valid, but it has not been updated for over a year.
Why chaining commands with pipes in Mac OS X does not always work
This problem has been bothering me for a long time so I finally took the time to figure out what was causing this issue.
No matter whether you use Mac OS X's built-in Terminal or a third-party application like iTerm, your shell may sometimes answer with a
command not found when you use a pipe to chain commands:
[mitro@MacBookAir ~]$ gem list --local | grep ^rails -bash: grep: command not found
Remove the spaces surrounding the pipes and it works:
[mitro@MacBookAir ~]$ gem list --local|grep ^rails rails (4.1.4, 4.1.0, 4.0.2)
What is happening here?
You are probably using a keyboard layout where you have to hold the
Alt-key to write a pipe (on german keyboard layouts a pipe is typed as
7). American layouts are not affected, I guess that's why it's hard to track this problem down on the net.
What is happening here is you not releasing the
Alt-key before pressing
Space. So you are typing a non-breaking space instead of a normal one which bash cannot interpret in this context.
How to track this down
Taking the erroneous command from above and piping it through
od gives a hint:
[mitro@MacBookAir ~]$ echo "gem list --local | grep ^rails" | od -t a 0000000 g e m sp l i s t sp - - l o c a l 0000020 sp | ? ? g r e p sp ^ r a i l s nl 0000040
So obviously the problem lies between the pipe and the following space. Copying and pasting this space (this is important to reproduce the error) and sending it through
hexdump shows that this is not a normal space character:
[mitro@MacBookAir ~]$ echo -n " " | hexdump 0000000 c2 a0 0000002
Doing the same with a regular space character looks the same but produces a different output:
[mitro@MacBookAir ~]$ echo -n " " | hexdump 0000000 20 0000001
A Google search for "Unicode c2a0" reveals that this is the code for a non-breaking space.
If switching to a different keyboard layout, slowing down your typing or reinstalling your operating system (yes, there are threads on the net where people suggest this) are no acceptable solutions for you, edit the file
.inputrc in your home directory (or create it if it does not exist) and add the following line:
"\xC2\xA0": " "
This maps non-breaking spaces to normal ones. The next time you start a new shell, this problem is gone.
Get in the loop
Join my email list to get new articles delivered straight to your inbox and discounts on my products.
No spam — guaranteed.
Got it, thanks a lot!
Please check your emails for the confirmation request I just sent you. Once you clicked the link therein, you will no longer see these signup forms.