Chapter 8
In This Chapter
.cshw scriptexit commandsource and direct executionWelcome to Part III. The first six chapters got you fluent at the prompt; the next four turn you into a script writer. By the end of Part III you'll be writing little programs that do real work — daily backups, log monitors, batch file renamers, deployment helpers. The shell stops being something you type at and becomes something you build with.
This chapter is your first script. We'll keep it small and clear so the mechanics are obvious. Chapters 9 and 10 add control flow (if/while/foreach) and procedures, the two pieces that turn linear scripts into proper programs.
A script is just a text file containing cshw commands, one per line. When you run a script, cshw reads the file from top to bottom and runs each command in turn, exactly as if you'd typed them at the prompt yourself. There's no compilation, no special syntax beyond what you've already learned, no magic. If a sequence of commands works at the prompt, you can paste it into a file, save it with a .cshw extension, and you've got a script.
The file extension matters — cshw recognizes .cshw files as its scripts, and after running install (Chapter 2), Windows knows about them too. We'll see how that wiring works below.
hello.cshwOpen your favorite text editor (Notepad works fine, VS Code is nicer, anything will do — it's just text). Type these two lines:
# My first cshw script
echo Hello from a cshw script!
Save it as hello.cshw in a directory you can find easily — your user folder or a Scripts subfolder is fine. The exact location doesn't matter; you just need to know where it is.
Open cshw, navigate to wherever you saved it, and run it:
cd C:\Users\You\Scripts
hello.cshw
You should see:
Hello from a cshw script!
That's it. You've written and run your first script.
TIP
You do not need to have run install for this. cshw looks for .cshw and .csh itself, in the current directory and along your PATH, whether or not anything has been registered with Windows. What install adds is the other direction: it puts .CSHW in the system PATHEXT and registers the file association, so that cmd.exe, PowerShell and Explorer can also start a script by name or by double-click. Inside cshw, hello and hello.cshw both work on a machine where nothing has been installed at all.
There's more than one way to ask cshw to run a script, and the differences matter. Here's the full inventory.
cshw finds .cshw and .csh files in the current directory and along your PATH, just as it finds .exe files, and runs them. So you can type the name:
hello.cshw # explicit extension
hello # implicit -- cshw tries .cshw and .csh for you
./hello.cshw # relative, the Unix habit
C:\Scripts\hello.cshw # absolute
hello.cshw one two # with arguments, which become the script's $argv
The shortcut form (no extension) is what makes scripts feel like first-class commands — once a .cshw file is on your PATH, you can call it like any built-in. An .exe of the same name still wins, because that is what PATHEXT order means and it is almost certainly what you meant.
There is one rule worth knowing, and it only matters when two files share a base name. A bare word asks the shell to find something, so it tries the extensions first: report reaches report.cshw. A word written as a path points at a file, so that file is tried first:
report.cshw the script
report a different, extensionless file with a #! line
report runs report.cshw -- you asked cshw to find one
./report runs report -- you pointed at that one
If the file you pointed at isn't there, a path falls back to the same extension search, so ./mytool still finds mytool.exe.
A script run this way is a separate shell. It gets its own variables and its own $argv; your environment (anything setenv has exported) crosses into it, and your plain shell variables do not. That is the difference between running a script and source-ing one, and it is important enough that it gets its own section at the end of this chapter.
A script with no extension at all. Scripts brought from Unix usually have no extension — they rely on the execute bit, which Windows does not have. cshw will still run one, provided it identifies itself the way Unix scripts do, with a #! first line:
#!/bin/csh -f
echo this runs
Save that as report, with no extension, and ./report runs it. cshw reads the #! line and honours it: if it names csh, tcsh or cshw, the script runs under cshw. If it names something else, cshw looks that up on your PATH and hands the script over —
#!/bin/bash # runs under bash, if bash is installed
#!/usr/bin/env python3 # runs under python
— and if the interpreter it asks for isn't there, you get one clear sentence saying which one is missing, rather than a screenful of syntax errors from the wrong language.
The #! line is required for an extensionless file, and that is deliberate. On Unix the execute bit decides what may run; Windows has no execute bit, so without some mark of intent, typing README at the prompt would execute your README as a program, line by line. A file must say what it is: either by its extension, or by #!. Anything else — notes.txt, README, data.bin — is not run, and cshw says so:
./README
ERROR: './README' is not a runnable image. To run it as a script, give it a
.cshw or .csh extension, or a #! first line.
cshw commandFrom cmd.exe, PowerShell, Windows Terminal, or anywhere else, run a script by passing it to the cshw executable:
cshw hello.cshw
cshw hello.cshw arg1 arg2 # pass arguments
cshw C:\Scripts\daily.cshw # absolute path
This is how you'd schedule a cshw script through Task Scheduler, or invoke one from a CI pipeline, or run it from any non-cshw context.
You can also use cshw -c "command" to run a single command without writing a script file:
cshw -c "echo Hello from outside cshw"
cshw -c "dir /b *.txt | wc -l"
-c is the right tool for "I want to use cshw's dir | grep | wc from a batch file" without committing to a .cshw file.
The extension is for Windows, not for cshw. cshw FILE runs FILE — whatever it's called:
cshw hello.cshw
cshw configure # no extension at all
cshw setup.tcsh # someone else's extension
.cshw and .csh matter for the file association, which is what makes double-clicking work (way 4 below) and what Explorer shows an icon for. Naming a file on the command line is a different question, and there the answer is the same as csh's: the file you named is the file that runs. This is worth knowing if you're bringing scripts over from a Unix machine, where extensions on scripts are the exception rather than the rule.
If you name something that isn't there, you'll be told, and cshw will exit non-zero rather than dropping you at a prompt:
cshw not-a-file
cshw: cannot execute 'not-a-file' (error 2)
And cshw --help lists the options cshw itself takes.
source (or .) — run in the current shellWe met source back in Chapter 5 when we talked about .cshrc. It runs a script's commands in the current shell rather than as a separate execution:
source setup.cshw
. setup.cshw # short form, same thing
Why does this matter? Because of variable scope. Read on.
After install runs, .cshw files are associated with cshw, so double-clicking one in Explorer opens a console window and runs the script. The window closes when the script finishes — which is fine for scripts that produce a file or show a dialog, but means you'll miss any console output that scrolled by too fast to read.
WARNING
Double-clicking a script is convenient, but it's the worst way to debug one. If the script fails immediately, the console flashes and closes before you can read the error. For development, always run from a cshw prompt — you'll keep the output visible, and you can re-run with arguments easily. Save double-clicking for scripts you trust.
source vs. Direct Execution: The Crucial DistinctionThis is the single most important thing in this chapter. Read it twice.
When you run a script directly (as a command, with cshw script.cshw, or by double-clicking), cshw creates a fresh execution context for it. Variables the script sets exist only for the duration of the script. When the script finishes, they're gone.
When you source a script, it runs in the current shell — there's no fresh context. Variables it sets stick around in your session. Aliases it defines remain defined. Procedures it declares are available afterward.
The practical demo:
Save this as setvars.cshw:
# setvars.cshw
set my_var = "Hello from setvars"
echo Inside the script: $my_var
Now try both ways:
setvars.cshw # direct execution
echo $my_var # empty -- the variable didn't survive
source setvars.cshw # sourced
echo $my_var # "Hello from setvars" -- it stuck
That's the whole distinction.
When to use which:
source for setup files — scripts that define aliases, set environment variables, load procedure libraries, or otherwise configure your current session. Your .cshrc is the canonical example.REMEMBER
If a script needs to change the shell that called it (set a variable, add an alias, change directories permanently), it must be sourced. If it should run as a standalone tool that doesn't affect the caller, run it directly. Mixing these up is the most common scripting confusion for newcomers.
Lines starting with # are comments. cshw ignores them entirely. Use them generously — your future self will thank you:
# My daily backup script
# Last edited: 2026-01-15
# Step 1: gather files
set source_dir = "C:\Projects"
set backup_dir = "C:\Backups"
# Step 2: copy them
cp -r $source_dir $backup_dir
# Done.
You can put a comment on its own line, after a blank line as a section header, or at the end of a command — the lexer treats # as "discard the rest of this line" at any token boundary, so echo hi # debug and echo hi #note both work. Whatever follows # to end-of-line is ignored.
echo Is Your FriendThe simplest way for a script to talk to the user is echo:
echo Starting the backup process...
echo Source: $source_dir
echo Done.
Anything echos goes to standard output, which means it shows up on the screen when you run the script interactively, gets captured by > when you redirect, and gets piped to the next command when you put your script in a pipeline. Just like any other command.
For more elaborate output you can use the full text-tools repertoire you learned in Chapter 6 — tee to capture as you go, > to log to a file, grep to filter — but echo is the workhorse.
TIP
Many scripts get into the habit of starting with a banner so it's clear what's running:
echo "=== Backup Script v1.2 ==="
echo "Starting at $(say time)"
echo ""
The blank echo "" produces a separator line. That kind of light formatting goes a long way toward making your scripts feel like real tools instead of stream-of-consciousness command lists.
Scripts get more useful the moment they take arguments. cshw provides positional arguments through the $1, $2, ... variables we saw in Chapter 5:
# greet.cshw
echo Hello, $1!
echo You are user number $2.
Run it:
greet.cshw Alice 42
# Output:
# Hello, Alice!
# You are user number 42.
The full set of argument variables cshw makes available inside any script:
$1, $2, $3, ... — individual positional arguments$argc — how many arguments were passed$argv — all arguments as one space-separated string (useful for "do something with all of them")A small example using all three:
# show_args.cshw
echo "Script got $argc arguments."
echo "First: $1"
echo "Second: $2"
echo "All: $argv"
Run with show_args.cshw apple banana cherry:
Script got 3 arguments.
First: apple
Second: banana
All: apple banana cherry
TECHNICAL STUFF
$argv is a word list, and you can index into it. Earlier printings said it was a string and that $argv[2] would not work; it does, and it is 1-based like every other subscript:
echo $argv[1] # apple -- same as $1
echo $argv[2] # banana -- same as $2
echo $argv[2-] # banana cherry -- "the rest of the arguments"
echo $#argv # 3
$1 and $2 are the shorter spelling for the first nine; $argv[n] keeps working past that, and the range form $argv[2-] has no $n equivalent at all. To iterate over every argument regardless of count, the foreach loop (Chapter 9) is still the clearest tool: foreach a ($argv) ... end.
$0 — the script itself$0 is the script cshw is running, as a full path. It is not part of $argv: $argv[1] is the first argument, and $#argv does not count the script.
echo $0 # C:\Users\you\tools\backup.cshw
echo `basename "$0"` # backup.cshw
Two everyday uses. The first is naming yourself honestly in a message:
if ($#argv < 1) then
echo "usage: `basename "$0"` SOURCE [DEST]"
exit 1
endif
The second matters more, and is the one people reach for late: finding out where you live. A script's working directory is wherever the shell happened to be, which is not necessarily where the script sits. That bites hardest when a script is launched by double-clicking it in Explorer — Windows starts it with its own idea of a working directory, and any source helper.cshw for a file sitting right next to your script fails.
$0 fixes that in one line:
cd `dirname "$0"` # work from where the script lives
source helper.cshw # ...so siblings resolve
cshw's own test runner does exactly this, for exactly that reason.
TECHNICAL STUFF
$0 is empty when there is no script: an interactive session, or cshw -c "...". Guard with if ("$0" != "") if a script might be used both ways.
TRY IT
Save greet.cshw (the two-line version above), then call it three different ways: with no arguments (notice the empty values), with one argument, and with three. See how $1 and $2 change.
Every script ends with an exit code — by convention, 0 means success and any non-zero value means some kind of failure. We met $? and $status back in Chapter 5 for reading exit codes; the other side of that coin is the exit command, which sets one as your script terminates:
# check_thing.cshw
if (-e "important.config") then
echo "Config found."
exit 0
endif
echo "ERROR: important.config is missing!"
exit 1
The if/endif syntax is Chapter 9, but you can see the shape: if the config file exists, we exit with code 0 (success). Otherwise we print an error and exit with code 1 (failure). The script's exit code becomes $? in whatever called the script — a parent shell, a calling script, Task Scheduler — so the caller can branch on success or failure.
A bare exit (with no number) exits with code 0:
echo "All done."
exit
exit from the top level of an interactive cshw session closes the shell entirely. Inside a script, it stops the script.
exit vs. retshell vs. retproc vs. returncshw distinguishes four "stop running this and unwind" verbs because the right one depends on what you want to stop:
| Verb | Scope it pops | When to use |
|---|---|---|
exit [N] |
The whole shell process | Top-level script wants to end; or you really want to close cshw |
retshell [N] |
A sourced script only — back into the parent shell |
A script invoked via source wants to bail without killing the interactive shell that sourced it |
retproc |
Just the current procedure frame | Inside a procedure, "stop running here; the rest of the script continues" |
return [N] |
Procedure frame + sets $result to N |
Same as retproc, but also delivers a return value to the caller |
exit inside a sourced script will close the parent shell — that's its whole point. retshell is the soft alternative when you specifically want the script to bail without killing the host. We'll see return again in Chapter 10 where procedures earn their full treatment.
REMEMBER
Exit codes are how scripts communicate with each other. A script that always returns 0 regardless of what happened gives the caller no way to know whether anything actually worked. Get into the habit of exit 1 (or 2, or whatever non-zero value documents the failure mode) on every error path.
By default, a script's output goes to whatever console launched it — visible on the terminal if you ran it interactively, attached to the parent process otherwise. For scripts you want to run silently (scheduled tasks, background data-collection scripts, anything that shouldn't clutter the user's screen), cshw provides three console-mode directives. Put one near the top of your script:
console quiet # suppress all stdout output
console hide # hide the console window entirely
console off # detach from the console entirely
console quiet — the script runs normally but its output to stdout is suppressed. The window is still there; commands still run; you just don't see what they print. Useful for "I want this script to do its job without spam."console hide — the script's console window is hidden. The script keeps running, but invisibly. Good for scripts launched on login or by Task Scheduler.console off (or console no) — the script detaches from the console entirely. Even more aggressive than hide.WARNING
console hide makes a script genuinely silent — including any errors it would normally print. Don't enable it until you've tested your script thoroughly in normal mode. A hidden script that crashes leaves you with no clue what happened.
TIP
During development, leave the console mode line out (or comment it out) so you can see the script working. Add it only when you're confident the script is correct and you want it to run unobtrusively.
Let's build a small but useful script that pulls together everything from this chapter: a backup script that copies a folder to a timestamped destination.
Save this as backup.cshw:
# backup.cshw — copy a folder to a timestamped backup location
#
# Usage: backup.cshw <source-folder> [destination-root]
#
# Example: backup.cshw C:\Projects\MyApp C:\Backups
# === Argument check ===
if ($argc < 1) then
echo "Usage: backup.cshw <source-folder> [destination-root]"
exit 1
endif
set src = $1
set dest_root = $2
if ($dest_root == "") then
set dest_root = "C:\Backups"
endif
# === Build a timestamped destination folder name ===
set stamp = $(say datetime /fmt:"%Y-%m-%d_%H-%M-%S")
set folder_name = $(basename $src)
set dest = "$dest_root\$folder_name-$stamp"
# === Do the backup ===
echo "Backing up $src"
echo " to $dest"
echo ""
mkdir $dest
cp -r $src\* $dest
if ($? == 0) then
echo ""
echo "Backup complete."
exit 0
else
echo ""
echo "ERROR: backup failed."
exit 1
endif
(A few of the pieces — if, basename-style path operations — are properly covered in later chapters; this is a preview. Don't worry if every line isn't 100% clear yet.)
What this script demonstrates, all in one file:
say and command substitution (Chapter 5) to compute a timestamp$? after a critical command to detect failureThat's a real, useful tool in about thirty lines. Run it:
backup.cshw C:\Projects\MyApp
And you get a timestamped folder under C:\Backups. Schedule it to run nightly via Task Scheduler and you have automated backups.
TRY IT
Type the script in, save it, and run it on any small folder you have. You should get a copy in a new timestamped folder. Try running with no arguments to see the usage message; try running with a bogus source path to see the error path trigger.
You've now got the basics — a script is a text file, it runs top to bottom, it can take arguments, and it returns an exit code. That's enough to write small linear scripts that do real work.
The next two chapters add the missing pieces:
if/else, while, do/while, loop N as i, and foreach. With these, your scripts can make decisions and repeat work. The if from the backup example becomes a proper building block.Together those three chapters — your first script, control flow, and procedures — are the entire foundation of cshw scripting. After Part III, you can read other people's cshw code and write your own.
For now: take a working command line from your shell history and turn it into a .cshw script. Anything you do regularly is a candidate. The first script you write that you actually keep using marks the point where cshw becomes more than a prompt — it becomes a way to automate.