Monday, November 21, 2005

Redirection

You ran your "hello, world" script like this:
 ./hello 
Output to a file, instead of the screen, is trivial.
 ./hello > foo 

What could be easier? Think of ">" as an arrowhead that points the output into a file. If the file doesn't exist, it's created.

The easiest way to learn the shell is to bounce back and forth between interactive and non-interactive uses. We'll start doing that now. First, create a "hello, world" script and run it.

echo "echo hello, world" > hello
chmod +x hello
./hello

Press the up-arrow key. The ./hello command will reappear, with your cursor at the end of the line, ready for you to type. Append the characters " > foo" and press ENTER. Then look to see what was put in the file foo.

./hello > foo
cat foo
Next, recall that command (./hello > foo), and use the backspace key to change foo to bar. Press ENTER and presto! now the output goes to bar.

Sending output to a file instead of to the screen is called "redirection." (The key to stage magic is misdirection, the key to shell magic, redirection.)

This is a common, and fruitful, way to develop shell scripts. While you're developing, let output go to the screen. When it's finally the way you want it, recall the command and redirect to a file to capture the output.

November 21 is World Hello Day, so rerun your program a few times, redirecting or not as fits your fancy.

0 Comments:

Post a Comment

<< Home