←  cshw: The C Shell for Windows

Chapter 23

Ten Tricks for When You're Stuck

In This Chapter

Every shell user, at some point in their day, finds themselves staring at a prompt thinking that should have worked. Sometimes you typed the wrong thing. Sometimes the shell parsed it differently than you expected. Sometimes a script hung. Sometimes a coroutine is doing something weird and you can't tell what.

This is the chapter for those moments. Ten tricks — none of them magic, all of them tactical — for narrowing the problem down fast.


1. Read the Error Message. Then Read It Again.

This is the trick that should be number one in every debugging chapter in every book about every tool, and almost never is. When something goes wrong, the shell usually tells you what went wrong. The message is right there. Read it.

fetch -o output.html https://api.example.com/data
fetch: cannot write to output.html: Permission denied

That message is fully diagnostic. The shell told you the operation (cannot write), the file (output.html), and the reason (Permission denied). The fix is obvious from the text. But under stress, the natural human response is to scroll past the message and start guessing — "is the URL right? is fetch installed? is the network up?" — when the answer is the file's permissions.

Read the message. Then read it once more. Most "I'm stuck" sessions end in the first thirty seconds with this trick alone.


2. Check $? — Did That Actually Work?

The shell doesn't always print "FAILURE" in big red letters. Some commands fail silently — they exit non-zero but don't produce error output, especially when stderr is redirected away. The exit status is the truth:

some_command > output.log 2>&1
echo "Exit: $?"

If $? is not 0, the command failed regardless of how things look. Always check after any command whose success matters — particularly inside scripts, where you might not see the on-screen output at all.

The defensive pattern:

some_command
if ($? != 0) then
    echo "Something went wrong with some_command"
    exit 1
endif

3. Sprinkle echo Statements as You Debug

cshw doesn't ship a full set -x-style command tracer the way bash does — but the classic technique still works: put echo statements at the lines where reality might diverge from your mental model, and watch the output stream tell you exactly what the script saw.

proc fetch_one
    echo ">>> fetch_one: arg1=$1"
    fetch -q "$1"
    echo ">>> fetch_one: status=$? result-len=$#result"
endproc

A handful of >>>-prefixed echoes around the suspicious region usually surfaces the bug in one re-run — and unlike a tracer, you control exactly what gets printed, so the noise stays manageable in scripts with thousands of iterations.


4. Print Variables — They're Lying to You

A surprising fraction of bugs come down to "the variable doesn't contain what I thought it contained." Print it:

set path = "C:\Program Files\My App"
echo "Path is: '$path'"

The quotes around '$path' are essential — they show you exactly where the variable's value begins and ends, including any leading or trailing whitespace. '$path' printed as ' C:\Program Files\My App ' (with spaces) is a different bug from 'C:\Program Files\My App' (without).

For arrays:

foreach i ($colors)
    echo "Element: '$i'"
end

For hashes:

foreach k (`hash keys config`)
    hash get config $k
    echo "$k = '$result'"
end

When you've inspected what's actually there, the bug usually becomes obvious.


5. Use tokenize to See What the Shell Sees

cshw has a built-in command specifically for "show me how you parsed this":

tokenize ls -la "my directory"/*.txt

It prints exactly how the shell broke your input into tokens — which words it saw, which strings were quoted, which got expanded. When a command line behaves unexpectedly, the cause is usually that your tokenization didn't match the shell's.

This is especially useful for quoting puzzles. cmd arg1 'arg with $var' arg3 — did the shell expand $var or keep it literal? tokenize will show you the answer in one line, without you having to actually run the command and figure it out from the output.

TIP

tokenize is a cshw-specific command. Most shells make you debug parsing problems by trial and error. cshw built a window into the parser, because parsing problems are real. Use it.


6. Bisect — Comment Out Half the Script

When a script "doesn't work" and you don't know where, divide and conquer. Comment out the bottom half:

# top half runs as before
...

# echo "OLD: bottom half disabled"
# do_the_questionable_thing
# more_stuff

Run it. If the problem disappears, it's in the commented half — comment out only the lower quarter, run again, repeat. If the problem stays, it's in the upper half — comment out the upper portion and rerun. Each iteration cuts the search space in half.

This works for 50-line scripts, 500-line scripts, and 5000-line scripts. Same algorithm, scales logarithmically. After at most five or six iterations, you've pinned down the offending lines.

REMEMBER

Bisect with the commented version saved — duplicate the script first, edit the duplicate. Otherwise, when you find the bug and fix it, you've also lost the working baseline. A cp script.cshw script.bak.cshw before any debugging session is a small habit with big payoffs.


7. which and where — What's Actually Running?

You typed mytool and something happened, but you're not sure which mytool. which and where are how you find out:

which mytool                # show the first match
where mytool                # show ALL matches (alias, function, executable, etc.)

where is the diagnostic: if you have mytool defined as an alias, and there's a mytool.exe on PATH, and a procedure called mytool from a sourced script, where shows all three. The order it prints them in is the order the shell resolves them:

proc  →  alias  →  built-in  →  PATH

The first line is what runs; everything below it is shadowed.

A common form of "weird behavior": you upgraded a tool, but the old version on PATH is winning over the new one. where makes this visible immediately.

Getting a built-in out of the way

Sometimes the thing shadowing your program is cshw itself. tree and vol are built-ins here and real programs in C:\Windows\System32; Git ships its own dir.exe. The built-in wins, which is deliberate — it's what makes a command mean the same thing on every machine, whatever else happens to be installed.

When you want the other one, just for now:

shadow tree                 # step the built-in aside
tree                        # now runs C:\Windows\System32\tree.com
unshadow tree               # put it back

shadow with no arguments lists what's currently hidden, and unshadow -a restores everything. Nothing is deleted — the built-in is set aside, never removed.

Two things worth knowing. If nothing on your PATH answers to the name, the name simply stops working:

shadow vol
vol                         # ERROR: 'vol' is not recognized ...

That's intended. shadow hides a command; it doesn't swap one in. And which will tell you exactly what's going on:

which tree                  # tree: cshw built-in command
shadow tree
which tree                  # C:\Windows\System32\tree.com (shadowed intrinsic)

An alias is a different thing and shadow won't touch it — use unalias for those, which it will tell you.

If you came from bash: enable

bash has had this feature all along under a different name. enable -n rm disables the built-in so the copy on PATH runs; enable rm puts it back. That is exactly what shadow and unshadow do, so cshw accepts bash's spelling too:

enable -n rm            # same as: shadow rm
enable rm               # same as: unshadow rm
enable                  # the built-ins currently in use
enable -n               # the ones that are hidden
enable -a               # all of them, with their state

The two spellings are the same mechanism, not two systems that happen to agree — a built-in hidden with shadow is restored by enable, and one hidden with enable -n shows up in shadow's listing. Mix them freely.

The listing format is bash's, and it is worth knowing why: every line is itself a valid command, so you can save the state and feed it back later.

enable -a > my-builtins.cshw
...
source my-builtins.cshw

None of the three will disable enable, shadow or unshadow. Each can undo the others' work, and a shell you can put into a state with no way out is a shell one bad line away from unusable.


8. History Recall — Get the Last Working Version

You've been fiddling with a command for ten minutes; you know it worked twenty minutes ago. history is the time machine:

history 50              # the last 50 commands
history 500 | grep ssh  # find the ssh you ran an hour ago

Up-arrow walks back through recent entries interactively; for older commands, history N plus a grep filter finds what you need. Copy the line that worked, paste it back at the prompt.

Even better — between sessions. cshw persists history across shell restarts, so "the version that worked last Tuesday" is still in there.


9. Concurrency Stuck? Clean It Out.

When you're using coroutines (Chapter 14) or synchronization primitives (Chapter 15), state can pile up — completed coroutines hanging around in the table, sync objects left over from a failed run, channels with unread messages. The result is "I run this and it does nothing," because the new coroutines are blocking on a leftover lock from a previous experiment.

The reset toolkit:

cocancel /all              # cancel any running coroutines
coclean                    # remove completed/cancelled entries
sync destroyall            # blow away all mutexes/events/semaphores/channels

This is the "clean slate" combo for concurrency state. Run it whenever you're at the prompt fiddling with coroutine code and want to start fresh.

For inspection without cleanup:

colist                     # what coroutines exist, and in what state
sync list                  # what sync objects exist
sync list channel          # filter by type

You'll often spot a stuck mutex or an unclosed channel just from listing.


10. Ask the AI

When you've checked the error message, looked at $?, traced the script, printed your variables, and still don't understand what's going on — genai is right there:

genai ask "What does this error mean: 'cannot find specified path'?"

# Better -- pipe the actual error in
some_command 2>&1 | genai ask "What's going wrong here?"

# Even better -- send the whole script along
genai analyze my_script.cshw "Why doesn't this work?"

This isn't admitting defeat; it's using a tool that's right there. Sometimes the AI gets it right immediately. Sometimes it gives you a hypothesis to test, which is still progress. Sometimes it suggests the obvious thing you'd been overlooking. All three are wins.

TIP

Pipe the error message and the command that produced it. echo "Tried: $cmd_text"; some_cmd 2>&1; echo "Exit: $?" followed by piping the whole thing into genai ask "diagnose this" gives the model real context. "Help me debug this error" with no context is worth less than the time it takes to type.


Bonus Tricks

A few more that earn their place but didn't make the top ten:


The Mental Model That Saves You

Every one of those ten tricks is really an instance of the same principle: gather information before acting.

The instinct when something doesn't work is to try changing things — flip a flag, rephrase a command, restart the program. Usually that's making the problem worse, because you don't yet know what was wrong with the original. The successful debugger pattern is the reverse: find out what's actually happening, then make a targeted fix.

That's what echo statements, tokenize, where, colist, "read the error message," and "ask the AI" all have in common. They're all ways of getting more information into your head before changing anything. Once you know what's actually going on, the fix is usually obvious — sometimes a one-character change. The hard part is the looking.

REMEMBER

Five minutes of inspection saves an hour of guessing. Every time.


The End of the Book

You made it. Twenty-two chapters and two appendices. From "open a shell, type ls" to "write a plugin DLL that exposes new commands to cshw and use them in a concurrent network scraper that calls an AI provider for classification."

Take a second to notice that. Most shell-scripting books take you halfway there — they cover the basics, maybe one or two advanced topics, and stop. This book has gone the full distance: filesystems, text processing, control flow, procedures, libraries, jobs, coroutines, synchronization, networking, AI integration, Windows API leverage, and plugin development. You've got the toolkit for almost anything anyone could reasonably ask a shell to do, and a lot of things that would normally require a "real programming language."

A few honest things to acknowledge as we close:

cshw is the work of one developer. You can find bugs. Some commands have rough edges. The plugin API is at v2 but still evolving. Take the polish with the rough — and if something genuinely doesn't work, file an issue. Open-source software gets better when people who use it carefully also report on it carefully.

This book is a snapshot. cshw evolves; commands get added, flags get refined, occasionally something gets renamed. The fundamentals (the shell's command-parsing model, the variable system, the coroutine model, the plugin API contract) are stable; the edges shift. When in doubt, help CMD and man CMD from inside the shell are the authoritative current reference.

You'll forget half of this. That's fine. The book is designed to be referenced, not memorized. Keep it on your desk; flip back to a chapter when a specific feature comes up. The cheat sheet (Appendix A) and command reference (Appendix B) exist exactly for that — quick lookup when the fingers know what you want but the brain has misplaced the exact syntax.

The real test isn't the book. It's whether, six months from now, when you have a real problem at work or a side project that needs automation, cshw is the tool you reach for. If it is — and it doesn't feel like a fight when you reach for it — then the book did its job.

Welcome to the shell. Go build something.

— fin