←  cshw: The C Shell for Windows

Chapter 6

Pipes, Redirection, and Command Chaining

In This Chapter

So far you've used commands one at a time. Each one runs, prints something, and you read the result. That's fine — but the real superpower of any Unix-flavored shell is composition: stringing small commands together so the output of one becomes the input of the next. A modern shell turns a handful of tiny, focused tools into something much larger than the sum of its parts.

This chapter is about the glue that makes that happen. By the end you'll be writing one-liners that do real work — log analysis, CSV manipulation, finding the most common errors, building reports — without writing a single script. (Scripts come in Part III, when one-liners stop being enough.)


The Pipe: |

A pipe takes the standard output of one command and feeds it directly into the standard input of the next. The syntax is a single vertical bar:

command1 | command2

The two commands run at the same time. command1 writes; command2 reads. The shell wires them together for you.

A trivial example:

help | grep -i hash

help lists every command cshw knows about. grep -i hash filters for lines mentioning "hash" (case-insensitive). What you see is just the hash-related commands — the rest gets filtered out before it ever reaches your screen.

You can chain as many commands as you want:

history | grep cd | tail -n 5

That reads "show my history, filter to just the cd commands, and show only the last five of those." Three tools, one pipeline, one question answered.

TIP

Pipes are the answer to "I wish that command had a --filter option." Most commands don't, because they don't need to — grep exists. Most commands don't have a --sort option either, because sort does. Once you internalize this pattern, you stop wishing commands had every possible option and start composing the option you need from the tools you already have.

TECHNICAL STUFF

cshw runs pipeline segments concurrently: help and grep execute at the same time through a real OS pipe, so grep starts filtering the moment help produces its first line instead of waiting for the whole thing to finish. That keeps memory flat and lets a long-running producer stream straight into its consumer. This is the default, and it's almost always what you want. If a script genuinely depends on the older behavior — each segment running to completion into a large in-memory buffer before the next one starts — you can opt back in, per-run or per-script, with set pipemode = sequential. The mode is snapshotted once when a pipeline starts, so flipping the setting from inside a running pipeline won't disturb the one already in flight.

TRY IT

At the prompt, type:

dir /b | sort | head -n 5

You just listed every file in your current folder, sorted them alphabetically, and showed only the first five. Three different programs cooperated to produce one answer.


Output Redirection: > and >>

Sometimes you want a command's output to land in a file instead of on your screen. That's redirection. The > operator points the output at a file:

dir /b > listing.txt
help > all-commands.txt

After those run, the matching content is in the file. Nothing was printed to the screen.

If the destination file exists, > truncates it — the old contents are gone, replaced by what the command just wrote. If you want to append instead, use >>:

echo "2024-01-15: built release 1.2" >> changelog.txt
date >> daily-log.txt

Each line gets tacked on to the end of the file, preserving whatever was already there.

You can combine redirection with pipes — the redirection happens at the end of the pipeline:

dir /b | sort | grep "\.txt$" > text-files.txt

That sorts the dir listing, keeps only .txt filenames, and writes the result to text-files.txt. Three commands cooperate, one file gets created.

WARNING

> overwrites silently. If you type dir > important-notes.txt and a file by that name already exists, its contents are gone. There's no Recycle Bin path for redirection overwrites. Get into the habit of glancing at the destination filename before you press Enter, and consider using >> (append) whenever you're not sure.

TIP

A safer pattern when building up a file is to write the initial content with > (deliberately wiping anything that was there) and append the rest with >>. Like a "BEGIN" marker followed by accumulating data:

echo "Build report" > report.txt
date >> report.txt
dir /b *.exe >> report.txt
wc -l *.cpp >> report.txt

Input Redirection: <

The < operator does the opposite: it feeds a file into a command's standard input, as if you'd typed the contents.

sort < unsorted-names.txt
grep ERROR < app.log

Most commands that read input also accept a filename directly — sort unsorted-names.txt and grep ERROR app.log do the same thing as the redirected versions. So when do you reach for <?

Mostly, when you've got a command that only reads stdin and doesn't take a filename:

genai ask < prompt.txt

If the command you're using only knows how to read from standard input, < is your bridge.

TIP

You can combine input redirection with output redirection in the same command:

sort < raw-data.txt > sorted-data.txt

Read from one file, write to another, without ever opening either explicitly. Both files are handled by the shell; the program in the middle just reads stdin and writes stdout.


Stderr Redirection: 2> and 2>&1

Commands actually produce two output streams: standard output (stdout, for normal results) and standard error (stderr, for diagnostics, warnings, and errors). When you redirect with >, only stdout gets captured — stderr keeps going to your screen.

That's usually what you want. But sometimes you specifically want to separate them, or combine them.

Separating errors from output

The 2> operator redirects stderr (file descriptor 2) to a file:

find /complicated/path 2> errors.log

That writes normal find results to your screen but stashes any "permission denied" errors in errors.log so they don't clutter the output you're trying to read.

Combining them

To merge stderr into stdout (so a pipe or > captures both), use 2>&1. The cryptic syntax reads as "redirect stream 2 to wherever stream 1 is going":

command > everything.log 2>&1
command 2>&1 | grep -i error

The first line writes both stdout and stderr to the same log file. The second pipes both streams through grep, useful when you want to filter all output regardless of which stream it came from.

TECHNICAL STUFF

The 2-and-1 are file descriptor numbers. 0 is stdin, 1 is stdout, 2 is stderr. So 2>&1 reads "make file descriptor 2 point to wherever file descriptor 1 currently points." It looks more arcane than it is. The order matters: command > file 2>&1 redirects stdout to the file first, then aims stderr at the same place. Reversed (command 2>&1 > file), stderr ends up at the original terminal.

The csh spellings: >& and |&

2> and 2>&1 come from the Bourne-shell family, and cshw supports them because everyone knows them. But this is a csh, and csh has had its own, shorter spellings for the same two jobs since the 1970s:

Bourne form csh form Meaning
> file 2>&1 >& file both streams to a file
>> file 2>&1 >>& file both streams appended to a file
2>&1 | next |& next both streams into the next command
build.cshw >& build.log            # everything, output and errors, in one file
make |& grep -i error              # filter both streams
find . -name "*.tmp" >>& audit.log # append both

They are shorter, and if you are porting a .cshrc or a csh script from a Unix box you will meet them constantly. Use whichever you find clearer — they compile to the same thing.

REMEMBER

There is no csh shorthand for "redirect only stderr". >& and |& always mean both. When you want stderr alone, 2> file is the form to reach for, and cshw supports it precisely because csh's own syntax has this gap.

Redirects work the same inside a pipeline

This deserves saying out loud because for a long time it was not true. Every form above means the same thing whether or not there is a pipe on the line:

stat missing.txt 2> errors.txt | wc -l      # errors.txt gets the diagnostic
stat missing.txt |& grep -c cannot          # 1 -- the merge reaches grep
source run_all_tests.cshw | tee suite.log   # the log has everything you saw

Until version 1.0.8.4 the middle two silently did nothing inside a pipeline: the message went to your terminal and the file or the next command got nothing. It was not a small bug — it meant a test suite could not be piped into a log file and read afterwards, which is most of what you would want a test suite for. If you have a script that worked around it, the workaround is no longer needed.

REMEMBER

A command can succeed and still write to stderr (warnings, info messages). A command can fail and write its error to stdout (poorly behaved programs). Stderr is a convention, not a hard rule. When in doubt, check $? for the exit code — that's the authoritative answer to "did it work?"


tee — Viewing and Saving at the Same Time

A redirection (>) sends output to a file instead of the screen. A pipe (|) sends it to another command. What if you want both?

tee is the answer. It reads stdin, writes a copy to one or more files, AND passes the same data through to stdout. Like a T-pipe fitting in plumbing — same data, two destinations.

build.cmd | tee build.log

While the build runs, you see its output scrolling by on the screen and it's being saved to build.log for later inspection.

You can put tee in the middle of a pipeline too:

longprocess | tee output.log | grep ERROR

That writes everything to output.log (for the record), while letting only the ERROR lines reach your screen.

To append rather than overwrite, use -a:

nightly-job.cmd | tee -a history.log

tee accepts multiple filenames if you want to write to several files at once:

command | tee log1.txt log2.txt log3.txt

TIP

tee shines for builds, deployments, and any long-running task where you want to watch progress and keep a record. The default > redirection makes a recording but you can't watch live; tee removes that tradeoff entirely.

TRY IT

Run dir /b | tee filelist.txt | wc -l. You'll see the count printed at the end (because wc -l ate all the file lines), but filelist.txt has the actual filenames. Two outputs from one command stream.


record — A Transcript of the Whole Session, Both Streams

tee copies one stream through one pipeline. record captures everything the shell does, on both streams, until you turn it off:

record build.log        start recording stdout AND stderr to build.log
record -a build.log     the same, appending to what's there
record off              stop
record                  say whether recording is on, and where

record is a mode, not a filter — it reads no input, so it never goes in a pipeline. cmd | record FILE is a mistake cshw will refuse rather than perform: it would throw away the output of cmd and leave the file collecting whatever happened next. One pipeline, tee. One session, record.

Nothing changes on screen — you still see the output as it happens. The difference from > file is the other stream. > captures stdout and lets every diagnostic through to your terminal, which is exactly backwards for keeping a record: the lines you most want to look at later are the ones that did not get saved.

record suite.log
source run_all_tests.cshw
record off

That file has the passing assertions and the diagnostics, in one place. Trying to get the same result with > gives you a file of successes and a terminal full of complaints, with no way to line them up afterwards.

TECHNICAL STUFF

Both streams go down one pipe, drained by a single reader, so the order they reach the pipe is the order in the file. That matters more than it sounds: two separate captures could never be reliably interleaved at all. What the shell has to do is make sure each command's buffered output reaches the pipe before the next command starts writing, because stdout is fully buffered once it is a pipe while stderr never is. It flushes at every command boundary for exactly that reason, so commands appear in the order they ran. Within a single command that writes to both streams, the last word or two can still cross; if that matters, 2>&1 first so there is only one stream left to order.

For a whole session — including the startup files, which a record command inside a script runs too late to catch — use the command-line switch:

cshw -record session.log myscript.cshw

TECHNICAL STUFF

record works at the stream level, below the individual command, which is why it also captures the output of external programs you run. It flushes as it goes rather than buffering, so if the shell hangs or you kill it, the transcript up to that moment is still on disk — which is usually the whole reason you started recording.

WARNING

A recording is not automatically a complete transcript. A command that redirects a stream for itself wins:

record session.log
risky.cshw 2> errors.txt      # those errors go to errors.txt, NOT to the recording

That is the right answer — the script said where it wanted them — but it means a transcript you attach to a bug report can be missing exactly the messages the bug is about. If you want everything in one file, take the 2> off, or point it at the recording's own name with >>&.

TIP

record and tee are not rivals, and they are not the same shape. tee is a filter: it sits in one pipeline you want to both watch and keep. record is a mode: it covers a session you want a transcript of. Reach for tee in a one-liner and record when you are about to do something you may need to explain afterwards.

NOTE

This command was called log through 1.0.8.4. It was renamed because the old name read as a synonym for tee and invited exactly the pipeline mistake described above. There is no log alias — the old name is gone. Unrelated: log(x) inside @ or awk is still the natural logarithm, and bc still spells it l(x).


The Text Toolkit: Tools That Shine in Pipelines

Chapter 4 introduced these briefly. Now that you've got the pipe under your belt, they earn their keep.

head and tail — first or last N lines

head file.txt              # first 10 lines (default)
head -n 20 file.txt        # first 20 lines
head -50 file.txt          # shorthand: first 50 lines
tail file.txt              # last 10 lines
tail -n 20 file.txt        # last 20 lines
tail -50 file.txt          # last 50 lines
tail -n +5 file.txt        # everything from line 5 onward (skip header)

tail also has a follow mode that's invaluable for watching log files:

tail -f application.log

-f keeps the file open and prints new lines as they're appended. Press Ctrl+C to stop. This is the standard "watch a log file in real time" idiom across every Unix-like shell, and cshw supports it.

TIP

tail -f log.txt | grep ERROR is the classic "alert me when something goes wrong" pattern. You see only the error lines, but the live tailing keeps watching forever.

sort — sort lines

sort names.txt              # alphabetical, ascending
sort -r names.txt           # reverse
sort -n numbers.txt         # numeric (so 2 sorts before 10)
sort -u data.txt            # sort AND remove duplicates
sort -f mixed-case.txt      # case-insensitive
sort -t, -k2 data.csv       # sort CSV by second column

The sort -u combination is the canonical "give me unique sorted lines" idiom — it does in one command what sort | uniq does in two, and it's faster.

uniq — collapse duplicates (but only adjacent ones)

This is the tool readers most often get wrong on first contact, so we'll get the gotcha out of the way:

uniq messy.txt              # only collapses ADJACENT duplicates
sort messy.txt | uniq       # what you usually want
sort -u messy.txt           # what you usually want, more concise

uniq compares each line to the one immediately before it. So if your duplicates aren't adjacent, uniq alone won't find them. Hence the sort | uniq pattern.

Useful flags:

sort log.txt | uniq -c      # count occurrences of each unique line
sort log.txt | uniq -d      # only show lines that appeared more than once
sort log.txt | uniq -u      # only show lines that appeared exactly once

uniq -c is half of the most famous shell idiom in existence — see "Composing Them" below.

cut — extract columns from each line

cut -d, -f1 data.csv               # first column of CSV
cut -d, -f1,3 data.csv             # first AND third columns
cut -d: -f1 colon-separated.txt    # first colon-separated field
echo "hello world" | cut -c1-5     # "hello" (characters 1-5)

cut is the lightweight alternative to awk when you just need column extraction. If your delimiter is a single character and you want a few specific fields, cut is faster to type. For anything more elaborate, awk wins.

tr — translate or delete characters

echo "hello" | tr a-z A-Z          # HELLO (uppercase)
echo "HELLO" | tr A-Z a-z          # hello (lowercase)
echo "hello   world" | tr -s ' '   # squeeze multiple spaces into one
echo "abc123" | tr -d '0-9'        # delete digits: abc
echo "a,b,c" | tr ',' '\n'         # turn CSV row into vertical list

tr is the smallest tool in the toolkit. It does character-level operations only — no regex, no fields, just "convert this set of characters to that set." But for those character-level jobs (case conversion, stripping unwanted characters, line-ending fixes), nothing is more concise.

TIP

Converting Windows line endings to Unix ones is the job you'd expect tr -d '\r' to do, and on a Unix shell it is. On Windows it needs sed -i instead:

sed -i 's/\r$//' windows-file.txt

The reason is worth understanding, because it applies to every redirect you write. > opens its target in text mode, and text mode turns every \n back into \r\n on the way out. So

type windows-file.txt | tr -d '\r' > unix-file.txt

leaves a file byte-identical to the original: tr really does delete the carriage returns, and the C runtime puts them straight back. The pipeline is correct; the redirect undoes it.

sed -i sidesteps that by rewriting the file in place rather than going through a redirect, so what it writes is what lands. The reverse conversion is sed -i 's/$/\r/'. Both belong in your toolbox for cross-platform work.

tr -d '\r' is still the right tool inside a pipeline -- type file.txt | tr -d '\r' | grep pattern works fine. It is only the final redirect to a file that puts them back.

rev — reverse characters within each line

echo "hello" | rev          # olleh

rev is niche. The classic use case is "sort files by extension" — you reverse each line, sort, then reverse back:

dir /b | rev | sort | rev

Files whose names share an extension end up adjacent because the reversed lines start with the (reversed) extension. It's a clever trick that pops up occasionally in real scripts.

REMEMBER

rev reverses characters within a line. The line order is preserved. To reverse line order (last line first), you'd want tac — covered next.

tac — reverse line order

tac is cat spelled backwards, and that's exactly what it does — reads its input and emits the lines in reverse:

type words.txt | tac           # last line first
tac log.txt                    # tac reads files directly too

The classic use is reading a log with the most recent entries on top:

tac /var/log/app.log | head -n 20

That gives you "the last 20 lines of the log, newest first." Pairing with a second tac gets you "the last N lines in original order":

tac access.log | head -n 5 | tac    # last 5 lines, oldest-to-newest

A tiny tool, but it earns its keep whenever you find yourself wishing sort -r worked on input that isn't sortable.


Composing Them: Real-World Pipelines

This is where it all clicks. A handful of canonical pipelines you'll recognize in any seasoned shell user's history.

Count something

dir /b *.cpp | wc -l

How many .cpp files in this folder? dir /b lists them, wc -l counts the lines.

Find the most common values

The famous "frequency count, descending" pipeline. Read every line that interests you, sort them (so duplicates become adjacent), uniq -c counts them, and sort -rn re-sorts by the count:

type access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn | head -n 10

That reads as: "from the access log, extract the first whitespace-separated field (the IP address), sort, count unique values, sort descending by count, show top ten." The top 10 most active visitors to your web server. Five tools, one line, real intelligence.

Filter and extract

type build.log | grep ERROR | cut -d: -f3 | sort -u

Read the build log, keep only ERROR lines, extract the third colon-separated field (likely the error message), sort to get unique messages. Now you know every distinct error your build produced, with no duplicates.

Skip headers

tail -n +2 data.csv | cut -d, -f1 | sort -u

Skip the CSV header row, extract the first column, deduplicate. Classic data-cleaning idiom.

Save while watching

build.cmd | tee build.log | grep -E "(error|warning)"

Build runs, full output goes to build.log, but only errors and warnings reach your screen so you can spot trouble while it's happening.

TRY IT

Run history to see your shell history. Then run history | cut -d' ' -f2 | sort | uniq -c | sort -rn | head -n 10. You just generated a "most-used commands" report on yourself. Try it after using cshw for a few days — the results are often surprising.


Shaping Text for Reading: nl, fold, fmt, pr

The filters so far change text. These four arrange it — for a screen, a page, or a printer. They are the last stop in a great many pipelines.

nl — number the lines

nl notes.txt
#      1<TAB>first line
#      2<TAB>second line

The default numbers only non-blank lines, six columns wide, then a tab. That is the difference between nl and cat -n, and it is usually what you want when numbering a document rather than a data file.

nl -ba notes.txt          # number blank lines too
nl -w3 -s': ' notes.txt   #   1: first line
nl -v100 -i10 notes.txt   # start at 100, count in tens
grep ERROR log.txt | nl   # number just the matches

fold — cut lines to a width

fold -w 40 notes.txt      # hard break at 40 columns
fold -s -w 40 notes.txt   # break at spaces, so words stay whole

fold cuts. Each input line is broken on its own, and a short line is left alone. Reach for it when line boundaries carry meaning and must not move.

fmt — reflow paragraphs

fmt notes.txt             # fill to 72 columns
fmt -w 60 notes.txt

fmt reflows: it joins a paragraph's lines back together and re-breaks them, so ragged text comes out evenly filled. Blank lines separate paragraphs and survive.

The distinction is worth fixing in your head, because the two look similar until you try them on the same file. Given three short lines:

result
fold -w 20 three short lines, unchanged
fmt -w 20 one filled line

Prose wants fmt. Fixed-width records want fold.

TECHNICAL STUFF

cshw's fmt fills greedily: each line takes as many words as fit. GNU's fmt aims at about 93% of the width and picks breaks that even out the whole paragraph, so its lines come out shorter and less ragged. On the same input at -w 30, GNU gave lines of 25, 27, 23 and 12 columns; cshw gives 30, 30 and 28. Both treat the width as a hard maximum and neither splits a word.

pr — paginate for printing

pr report.txt                       # date, title and page number on each page
pr -h "Quarterly Summary" report.txt
pr -t report.txt                    # no header at all
pr -tn report.txt                   # no header, numbered lines

pr is the formatting front end for printing: it adds a header carrying the date, a title and a page number, and pads each page to a fixed length. In scripts the form you will write most is pr -t, which strips all of that and leaves pr as a plain filter.

Put together, the four chain naturally:

fmt -w 65 letter.txt | pr -h "Draft" | lp

Reflow the prose, paginate it with a title, send it to the printer.

⚠️ Not implemented — pr's multi-column options (-2, -3, …) are not supported. Passing one is an error, not a silent no-op, so a script that needs columns fails where you can see it rather than quietly producing single-column output that looks nearly right.

TECHNICAL STUFF

These four are cshw built-ins, and that is a deliberate fix rather than a detail. They used to be missing, which was invisible on a developer's machine: Git for Windows ships its own pr.exe, fold.exe, fmt.exe and nl.exe and puts them on PATH. A script piping through pr therefore worked on a machine with Git installed and failed on a clean Windows box — and no test could tell the two apart. Now the behaviour is the shell's own, wherever it runs. which pr will tell you which one you are getting.

Command Chaining: ;, &&, and ||

What if you want to run several commands in a row but the relationship isn't a pipe? You don't need each one's output to feed the next — you just want them to happen in sequence.

; — run, then run

The semicolon runs commands one after another, regardless of whether the previous one succeeded:

cd Projects ; ls ; pwd

That changes directory, then lists, then prints the working directory. Three independent commands, one line, but no pipeline — each runs to completion and prints to your screen normally.

&& — run the next one only if the previous succeeded

&& makes the second command conditional on the first succeeding (exit code 0):

mkdir build && cd build && cmake ..

If mkdir build fails (maybe the folder already exists), neither cd nor cmake runs. If all three succeed, you've made a folder, moved into it, and started a build. The chain stops at the first failure.

|| — run the next one only if the previous failed

|| is the mirror image: run the second only if the first failed:

which git || echo "git is not installed"

If which git finds git, the echo doesn't run. If it doesn't find git, you get the message. The classic "fall back to a default" pattern.

Combining them

&& and || combine in obvious ways:

make && echo "Build OK" || echo "Build FAILED"

If make succeeds, you see "Build OK". If it fails, you see "Build FAILED". The pipeline stops as soon as the conditional dictates.

TIP

In bash, && and || are sometimes used as a substitute for if/then/else. cshw has a real if statement (Chapter 9) which is much clearer for anything beyond a one-line conditional. Use && and || for the simple cases (single-line guards, fallbacks); reach for if when you're branching anything substantial.

Word forms: and, or, xor, nor, nand

When the symbols feel terse, cshw accepts spelled-out chainers as standalone whitespace-bounded tokens:

and and or are pure aliases for && and || — pick whichever reads better:

mkdir build and cd build and cmake ..
which git or echo "git is not installed"

xor is the unusual one. Because it has to know the result of both sides to compute "exactly one succeeded," it can't short-circuit — both commands always run, with all their side effects:

build_release xor build_debug    # both run; success only if exactly one worked

nor and nand invert the final status compared to their &&/|| cousins. You'll reach for them less often than and/or, but they're there when the logic naturally inverts ("succeed only if neither did").

REMEMBER

Word chainers must be whitespace-bounded standalone tokens. andrew and xorvalue stay as identifiers — they don't get parsed as and rew or xor value. Only <space>and<space> (or or / xor / etc.) between two command segments triggers chainer behavior.

WARNING

xor's eager evaluation makes it the surprise of the family. Writing dangerous_cmd xor safe_cmd runs dangerous_cmd every time, even when your mental model says "the xor will short-circuit." When in doubt, an explicit if from Chapter 9 reads more honestly than xor ever will.


When a Pipeline Becomes a Script

There's a point in every shell user's life where a pipeline gets too long, too complicated, or too hard to remember. You find yourself recalling the same multi-step command from history every day. Or you want to add an if somewhere in the middle. Or the pipeline has hardcoded values you keep editing.

That's the moment a pipeline graduates into a script. cshw makes that transition easy — Part III of the book covers scripting in depth, including how to take a working one-liner and turn it into a reusable command with parameters.

The signs that it's time to script:

When any of those start applying, flip ahead to Chapter 8 and write your first .cshw script. The world of one-liners is still there for the small stuff, but you've got better tools now.


Onward

You now have the shell composer's toolkit: pipes for chaining, redirection for files, tee for splitting streams, and a half-dozen tiny text-processing tools that do their one job well. You can write one-liners that count, filter, summarize, and transform real data without leaving the prompt.

Chapter 7 covers history, tab completion, and the prompt — the small ergonomic features that turn "shell I use" into "shell I enjoy." After that, Part III opens with your first script, where these one-liners get parameters, names, and a permanent home.