Chapter 10
In This Chapter
proc and endproc$1/$2/$argc/$argv, or named parametersset leaks out and when to use localreturn and $resultlibrary directiveYou've now got the full set of building blocks: data (variables, arrays, hashes), flow (if, while, for, foreach, switch, break, continue), and a way to run scripts as standalone tools. What's missing is organization. As scripts grow past a screen of code, the same chunks of logic start showing up in three or four places. That's the moment to package them into procedures — named, reusable pieces of code that can be called from anywhere in the script.
This chapter is about procedures and the libraries you build out of them. By the end, you'll be able to factor a sprawling script into reusable pieces and load a personal collection of helpers across every script you write.
The basic shape is:
proc PROCNAME
# statements that make up the procedure body
endproc
A complete first example:
proc greet
echo "Hello, $1!"
endproc
That defines a procedure called greet. The body runs only when the procedure is called — defining it just registers it.
To call it, type its name followed by arguments, exactly like a built-in command:
greet World
# prints: Hello, World!
greet "Tarie Nosworthy"
# prints: Hello, Tarie Nosworthy!
cshw recognizes greet as a procedure call (it checked the procedure registry, found a match) and runs the body with the arguments bound to $1, $2, and so on.
The body can be as many statements as you want, including control flow:
proc backup_one
if (-f "$1") then
echo "Backing up $1..."
cp "$1" "$1.bak"
else
echo "Skipping $1 (not a regular file)"
endif
endproc
backup_one config.ini
backup_one notes.txt
backup_one missing.cfg
Each call runs the full body afresh. The if, cp, and echo work exactly as they do at the script top level — there's no special "inside a procedure" mode.
Inside a procedure body, cshw makes the call's arguments available three different ways. Pick whichever reads most clearly.
$1, $2, $3, ...This is the simplest and most common. Whatever arguments the caller passed are bound to $1, $2, $3, and so on:
proc add
@ sum = $1 + $2
echo "$1 + $2 = $sum"
endproc
add 7 5
# prints: 7 + 5 = 12
$0 is not the procedure name (cshw uses $1-indexed positionals).
$argc and $argv$argc is how many arguments were passed; $argv is all of them as a space-separated string. Both are scoped to the procedure call — they don't leak out:
proc show_call
echo "Called with $argc arguments: $argv"
endproc
show_call apple banana cherry
# prints: Called with 3 arguments: apple banana cherry
$argc is especially useful for procedures that take a variable number of arguments:
proc print_all
if ($argc == 0) then
echo "(nothing to print)"
return
endif
foreach a ($argv)
echo "- $a"
end
endproc
print_all
print_all one two three
proc NAME(p1, p2)For procedures with a fixed argument list, you can name the parameters and refer to them by name inside the body:
proc divide(numerator, denominator)
if ($denominator == 0) then
echo "Error: division by zero"
return
endif
@ result = $numerator / $denominator
echo "$numerator / $denominator = $result"
endproc
divide 100 4
# prints: 100 / 4 = 25
Named parameters are sugar — they coexist with the positional $1/$2. Inside divide, $numerator and $1 refer to the same value; $denominator and $2 refer to the same value. Use whichever reads better at the call site.
TIP
Named parameters pay off when a procedure has more than two arguments. proc connect(host, port, timeout, retries) is much easier to read inside the body than four $1/$2/$3/$4 references that all look the same. For short procedures with one or two arguments, the positional form is fine.
TRY IT
Save and run this:
proc max(a, b)
if ($a > $b) then
echo "$a is larger"
else
echo "$b is larger"
endif
endproc
max 10 7
max 3 8
max 5 5
Here's where procedures get subtle — and where the most common surprises live. Three rules:
$1, $2, $argc, $argv, and named parameters are local to the call. They exist only during the procedure body. After the procedure returns, they're gone. If two procedures both use $1, they don't interfere.set inside a procedure modifies global state by default. A set my_var = "value" inside a procedure body writes to the global variable namespace, where the caller can read it after the procedure returns. This is not the same as most other languages — heads up.local.Demonstrating rule 2 first:
proc setter
set message = "hello from inside"
endproc
# Before the call -- no such variable
echo $message
# (empty line)
setter
# After the call -- the variable is visible globally
echo $message
# prints: hello from inside
The set inside setter wrote straight through to the global namespace. That's the default behavior, and it's how procedures most commonly communicate results back to the caller. Conventional pattern: agree on a variable name, set it inside the procedure, read it after the call.
If that's not what you want — if you want a working variable that exists only during the procedure call — use local:
proc compute
local temp = 0
local result = 0
@ temp = $1 * 2
@ result = $temp + 1
set final_answer = $result
endproc
compute 5
echo $final_answer # 11 -- visible
echo $temp # empty -- local, gone
echo $result # empty -- local, gone
temp and result are working scratch space that doesn't pollute the caller's namespace. final_answer uses plain set, so it survives the procedure call and is visible afterward.
REMEMBER
Default set inside a procedure writes through to globals. That's a feature — it's how procedures return their work to the caller — but it can also clobber a caller's variable by accident. Use local for working variables, and set only for the values you genuinely want the caller to see.
WARNING
local only works inside a procedure. At the top level of a script (or at the interactive prompt), local x = 5 will refuse. If you find yourself wanting local outside a procedure, your script is asking to be refactored into one.
return and $resultcshw procedures have two distinct ways to communicate a value back to the caller. Both are common, and they're complementary.
return $value and $resultThe return statement exits a procedure immediately. If you give it a value, that value lands in the special global variable $result:
proc square
@ value = $1 * $1
return $value
endproc
square 7
echo "Result: $result"
# prints: Result: 49
return without an argument exits the procedure with no value; the caller's $result will be empty.
This pattern is the closest thing to a "function returns a value" in a conventional language. The proc treats itself as if it computes one thing; the caller reads $result afterward.
Equivalent and often clearer, especially when a procedure produces several outputs: just set whichever global variables the caller is expecting:
proc parse_full_name
set first_name = $1
set last_name = $2
endproc
parse_full_name "Ada" "Lovelace"
echo "First: $first_name"
echo "Last: $last_name"
No return needed; set already wrote through to globals.
return $value when the procedure naturally has one answer and you want consistent calling conventions. Easy to call: proc_name args ; use $result.set of named globals when the procedure produces multiple results, or when the existing variable names make the code read more naturally.Mixing them is fine. A procedure can set some named globals AND return a primary result:
proc divmod
@ quot = $1 / $2
@ rem = $1 % $2
set remainder = $rem
return $quot
endproc
divmod 17 5
echo "$result quotient, $remainder remainder"
# prints: 3 quotient, 2 remainder
Whether a procedure used return or not, it also has an exit status, which surfaces as $? / $status in the caller:
proc validate
if (-f "$1") then
true # status 0
else
false # status non-zero
endif
endproc
validate config.ini
if ($? == 0) then
echo "config.ini is fine"
endif
return without a value preserves whatever exit status was last set inside the procedure. So you can mix-and-match: a procedure can return a value via $result AND signal success/failure via its exit status.
TECHNICAL STUFF
Recursion works exactly as you'd expect. Each call gets its own $1/$2/$argc/$argv and its own local variables, while global sets accumulate across the call stack. A factorial procedure that calls itself is a classic three-liner:
proc factorial
if ($1 <= 1) then
set fact = 1
else
@ n_minus_1 = $1 - 1
factorial $n_minus_1
@ fact = $1 * $fact
endif
endproc
The trick is that fact is global, so each level of recursion writes the running product to the same variable. Read by the outermost caller after factorial N, $fact holds N!.
A single script with a handful of useful procedures is great. A collection of procedures you can reach for from every script you write is better. That's what libraries are for.
cshw gives you two complementary mechanisms:
library NAME as a directive at the top of a file — marks that file as a library. Running it directly only registers its procedures; it doesn't execute any top-level code.library FILE as a command — loads procedures from another file into the current shell, without executing that file's top-level code.Together they form the package system: you write libraries as .cshw files with the library directive at the top, and you load them with the library command from any script (or .cshrc) that wants to use them.
Save this as mathlib.cshw:
library mathlib
#
# A small math helpers library.
#
proc square
@ v = $1 * $1
return $v
endproc
proc cube
@ v = $1 * $1 * $1
return $v
endproc
proc max(a, b)
if ($a > $b) then
return $a
else
return $b
endif
endproc
proc clamp(value, low, high)
if ($value < $low) then
return $low
else if ($value > $high) then
return $high
else
return $value
endif
endproc
The first non-comment line — library mathlib — flags the file as a library. The name after library is informational; cshw uses it for diagnostics. If you ran mathlib.cshw directly at the shell, nothing visible would happen — the procedures get registered but nothing calls them, and the library directive suppresses any top-level execution.
From another script (or from the prompt, or from .cshrc):
library mathlib.cshw
square 7
echo "7 squared = $result"
cube 4
echo "4 cubed = $result"
clamp 150 0 100
echo "clamp(150, 0, 100) = $result"
The library command loads mathlib.cshw, registers its procedures, and from that point onward square, cube, max, and clamp are available like any built-in command.
You can load multiple libraries at once:
library mathlib.cshw stringlib.cshw datelib.cshw
Order matters if libraries depend on each other — load base libraries first.
A common pattern: keep a cshw_lib directory under your user profile or in a project, and load whatever you need at script startup:
# in any script that wants math + string helpers
library C:\Users\You\cshw_lib\mathlib.cshw
library C:\Users\You\cshw_lib\stringlib.cshw
# ... script that uses them ...
Or load them once in .cshrc so every interactive session has them ready:
# in .cshrc
library C:\Users\You\cshw_lib\mathlib.cshw
library C:\Users\You\cshw_lib\stringlib.cshw
Now at any prompt you can call square 5 and read $result — no per-session loading needed.
TIP
Libraries should contain only procedure definitions and (optionally) set calls for constants. Avoid putting executable logic at the top level of a library file — even with the library directive suppressing it on direct execution, the directive only takes effect when the file is recognized as a library. If you ever forget to add library NAME at the top, your top-level code will run unexpectedly. Procedure-definitions-only files dodge that footgun.
REMEMBER
library and source are different. source FILE executes the file's commands in the current shell — top-level statements run, variables get set, the whole thing. library FILE loads procedure definitions only — top-level statements don't run. For a .cshrc-style configuration file, use source. For a procedure-only helper file, use library.
TRY IT
Save the mathlib.cshw above (or one of your own). Then from any cshw prompt: library mathlib.cshw, then square 12, then echo $result. You should see 144. Now close the shell, open a new one, and try square 12 directly — you'll get a "command not found" until you load the library again. Add library C:\path\to\mathlib.cshw to your .cshrc to have it always available.
Let's build something genuinely useful. Save this as datelib.cshw:
library datelib
#
# Date and timestamp helpers built on top of `say`.
#
proc timestamp
# YYYY-MM-DD_HH-MM-SS -- filename-safe, sorts chronologically
set _ts = $(say datetime /fmt:"%Y-%m-%d_%H-%M-%S")
return $_ts
endproc
proc today
# Today's date, ISO-style: YYYY-MM-DD
set _d = $(say date /fmt:"%Y-%m-%d")
return $_d
endproc
proc nowtime
# Current time, HH:MM:SS
set _t = $(say time /fmt:"%H:%M:%S")
return $_t
endproc
proc pretty_date
# Friendly date, e.g. "Saturday, May 16, 2026"
set _d = $(say date /fmt:"%A, %B %d, %Y")
return $_d
endproc
proc log_line(message)
# Prefix a message with [YYYY-MM-DD HH:MM:SS]
set _stamp = $(say datetime /fmt:"%Y-%m-%d %H:%M:%S")
echo "[$_stamp] $message"
endproc
Load it and use it:
library datelib.cshw
today
echo "Today is $result"
pretty_date
echo "Or, more formally: $result"
log_line "Build started"
sleep 2
log_line "Build finished"
You should see output like:
Today is 2026-05-16
Or, more formally: Saturday, May 16, 2026
[2026-05-16 14:23:01] Build started
[2026-05-16 14:23:03] Build finished
Five procedures, one file, every cshw script you write going forward can now log timestamps and grab dates without reinventing the format string each time. That's the payoff of libraries — accumulated useful code that follows you across projects.
A few habits that pay off as your library collection grows:
mathlib.cshw does math. stringlib.cshw does strings. datelib.cshw does dates. Keep them focused; load only what you need.parse_log_entry is much better than parse. Library procs live in the global namespace alongside built-ins, so name them with enough specificity that you won't accidentally shadow cd or set.local variables with _. A leading underscore (local _temp = 0) makes it obvious in the body that it's working scratch space, and reduces the chance of accidentally colliding with a caller's variable name if local were ever to be forgotten.library NAME directive is your safety net, but procedure-only files don't depend on it..cshrc for procedures you use every day; load them per-script for project-specific helpers.That's the full Part III complete. You now know how to:
Linear scripts → branching scripts → modular scripts. The progression mirrors the way actual programs are built; cshw just gives you the syntax to do it without leaving the shell.
From here, the chapters build toward what makes cshw interesting — the features that genuinely set it apart from other shells. Chapter 11 rounds out data handling (arrays and hashes), and Chapter 12 covers arbitrary-precision math with bc and dc. Then the power features arrive: job control and background processes (Chapter 13), coroutines and real parallelism (Chapter 14), synchronization primitives (Chapter 15), networking (Chapter 16), AI integration via genai (Chapter 17), and the plugin API for extending cshw with your own C++ DLLs (Chapter 18). The shell stops being a productivity tool and starts being a platform.
But that's for later. For now, you've got everything you need to be productive. Open a fresh .cshw file, write something useful, save it where you can find it again, and that's the rest of your shell life sorted.
Bring your .cshrc. From here, every chapter is icing.