Pipes

From PrgmrWiki

this page is part of the ongoing 'prgmr.com *NIX education program' - as time goes on, I'd like to organize these pages into a self-support resource for people learning *NIX.

a pipe, the | character (shift backslash on most US keyboards) is a way of redirecting data on the linux command line.


To understand pipes, you first need to understand that *NIX command line processes often use two standard filehandles... standard in, STDIN, which is where data imput into the program goes if not otherwise redirected, and standard out, or STDOUT, which is where output goes, if not otherwise redirected.

the command

echo "test"

outputs the string

test \n

on STDOUT.

the command

echo "test" |cat

does the same, as with no arguments, cat reads STDIN and writes to STDOUT.

cat /home/lsc/.ssh/id_rsa.pub

will print the contents of /home/lsc/.ssh/id_rsa.pub on stdout, as if you pass cat a filename, it reads from the file rather than STDIN.

so say I want to copy my ssh public key to another server. One way to do it is

cat /home/lsc/.ssh/id_rsa.pub |ssh lsc@newserver.prgmr.com "cat >/home/lsc/.ssh/authorized_keys"

What is this > character you ask? that is the redirect operator. If you type > filename after a command, STDOUT is redirected to filename. So > is a little like | only instead of feeding stdout into stdin of a new program, it prints it to a file.

If you use cat test > file it will erase file and overwrite it with the contents of test. If you cat test >> file then the contents of test are appended to the existing file.