Chapter 5
In This Chapter
set, unset) and how cshw infers typessetenv, unsetenv, printenv, env)$?, $status, $:, $$, and friends)@readonly, local, declare.cshrcSo far you've used the shell as an interactive command runner — you type a thing, it does the thing, you move on. That's a perfectly valid mode and many people never leave it. But the moment you want to remember something — a path you keep typing, a result you'll need in the next command, your favorite shortcut — you need variables. And once you have variables, you have the raw material for everything else cshw can do: scripting, automation, customization, the whole package.
This chapter is where the shell starts being yours instead of generic. By the end you'll know how to store things, recall them, customize the environment, and define your own command shortcuts. We'll also meet a small cast of special variables that cshw maintains automatically and that turn out to be enormously useful.
setThe most basic kind of variable lives only inside your shell. To create one, use set:
set name = "Tarie"
set count = 42
set greeting = "Hello, world"
To use the value, prefix the name with $:
echo $name
echo "Hi $name, you have $count messages"
cshw accepts three equivalent forms for set, so you can use whichever feels natural:
set name = "Tarie" # spaces around the equals sign
set name="Tarie" # no spaces, all together
set name "Tarie" # no equals sign at all (csh-style)
All three create the same variable.
REMEMBER
Variable names are case-sensitive. $Name, $name, and $NAME are three different variables, just like in most programming languages. This trips up Windows users who expect path and PATH to be the same; for shell variables in cshw, they aren't.
To see every variable cshw currently has set, run set with no arguments:
set
You'll get a list. To check just one, use echo:
echo $name
And to remove a variable, unset:
unset count
echo $count # now expands to empty
cshw notices the kind of value you assign and tracks its type. Strings, integers, and floating-point numbers are all stored as their proper types under the hood, which matters mostly when you do arithmetic (see the @ section below).
To check the inferred type, use vartype:
set n = 42
set f = 3.14
set s = "hello"
vartype n # Variable 'n' is of type Integer.
vartype f # Variable 'f' is of type Floating Point.
vartype s # Variable 's' is of type String.
TIP
Most of the time you won't think about types. The shell does the right thing automatically. The only time it really matters is when you do math on what looks like a number — if it was stored as a string, you'll get string concatenation instead of addition. vartype is the quick diagnostic when something surprises you.
TRY IT
Run set myname = "<your name>", then echo "Hello, $myname!". Now run set count = 5, then set count = $count + 1, then echo $count. You'll get 5 + 1, not 6 — that's because set does string assignment, not arithmetic. For arithmetic, you need @, which we'll see in a moment.
setenvA shell variable lives only inside your shell. An environment variable is a different beast: it gets inherited by any program your shell launches. When you type git status, the git.exe process inherits a copy of your shell's environment — its PATH, its TEMP, anything you've set via setenv.
To set one:
setenv MY_APP_DIR "C:\Tools\MyApp"
setenv JAVA_HOME "C:\Program Files\Java\jdk-17"
To see them all:
setenv # or: env, or: printenv
To see just one:
setenv PATH # shows PATH=...
printenv PATH # shows just the value, no NAME=
And to remove:
unsetenv MY_APP_DIR
REMEMBER
Environment variable names on Windows are case-insensitive. setenv PATH "...", setenv Path "...", and setenv path "..." all modify the same variable. That's Windows behavior, not cshw quirkery — every program on Windows sees environment variables this way. Note how this differs from shell variables (which are case-sensitive); when working with both, that asymmetry is worth keeping in mind.
The env command has a clever trick: you can use it to run a command with extra environment variables, just for that command, without changing your shell's environment:
env DEBUG=1 myprogram.exe # run myprogram with DEBUG=1
env PATH="C:\Tools;%PATH%" tool.exe # run tool with a modified PATH
env -u PROXY myprogram.exe # run with PROXY unset
env -i program.exe # run with empty environment
Once the command finishes, your shell's environment is exactly as it was before. This is genuinely useful for "I want to test this program with one variable changed without polluting my session."
This is the question that confuses everyone, so let's nail it down concretely.
set my_shell_var = "I am a shell variable"
setenv MY_ENV_VAR "I am an environment variable"
echo $my_shell_var # works inside this shell
echo $MY_ENV_VAR # also works inside this shell
# Now launch a child process:
cshw # opens a nested cshw
echo $my_shell_var # empty -- did NOT survive into the child
echo $MY_ENV_VAR # "I am an environment variable" -- survived
That's the entire distinction. Shell variables are private to your shell session. Environment variables get passed down to every child process you launch.
When to use which:
set): for personal bookkeeping inside your current session. Things like temporary paths, intermediate results, loop counters, anything other programs don't need to see.setenv): for configuration that programs you launch will read. PATH, JAVA_HOME, anything your_program.exe checks via GetEnvironmentVariable.TECHNICAL STUFF
Neither kind of change persists past the shell exiting. To set an environment variable permanently, you need to use Windows' System Properties dialog or the setx command (different from setenv!). cshw can also write to the persistent environment via its registry env export NAME command — that updates HKCU\Environment and broadcasts the change so other running processes notice. That's beyond Chapter 5's scope; for now, just know that setenv is for the current session.
A variable reference is part of a word, not a word of its own. This is the single most common thing you'll write:
set dir = reports
set file = march
echo $dir/$file.csv # reports/march.csv
echo $dir-backup # reports-backup
echo $file$file # marchmarch
echo prefix-$file # prefix-march
Everything glued to the reference — before it, after it, another reference — belongs to the same argument. cshw resolves the reference and hands the whole word along as one thing.
${name}The braces exist for the case where the text after the reference could be read as part of the name:
set p = report
echo $ptotal # looks for a variable called "ptotal" — empty
echo ${p}total # reporttotal
Use them whenever a letter, digit or underscore follows the name. Anywhere else they're optional, and ${p}/x and $p/x mean the same thing.
Both expand. The difference is what happens after:
set cmd = "wc -l"
set pat = "*.log"
echo $cmd # two words: wc and -l
echo "$cmd" # one word: "wc -l"
echo $pat # the .log files in this directory
echo "$pat" # the two characters *.log
An unquoted expansion is split on whitespace and then filename-matched, which is what makes set files = "*.txt" followed by $files useful. A quoted one is left exactly as it came out. Reach for the quotes when the value is one thing that might contain a space — a path under C:\Program Files, most obviously.
$A backslash makes a dollar sign a dollar sign:
echo \$HOME # $HOME
echo "Total: \$5.00" # Total: $5.00
echo 'Total: $5.00' # Total: $5.00
Single quotes do it wholesale — nothing inside them expands. The backslash does it for one character, and works inside double quotes too. The same applies to a backtick you want printed rather than run: \`.
Some variables you don't set — cshw sets them automatically and keeps them up to date. They're enormously useful in scripts and one-liners.
$? and $status — exit code of the last commandWhen a command finishes, it returns an exit code. By convention, 0 means success and anything else means some kind of failure. cshw stores the most recent exit code in two variables that mean the same thing: $? (the Bourne shell name) and $status (the csh name).
ls C:\some-folder
echo $? # 0 if it worked, non-zero if not
This is the foundation of scripted error checking, which we'll do a lot of in Part III.
TRY IT
Run ls C:\nonexistent\folder (a folder you know doesn't exist). Then echo $?. You'll see a non-zero number. Then run ls (no arguments — which lists the current directory). Then echo $? again. Zero. That's how you know whether the previous command worked.
$: — current working directoryThe colon-variable holds your current directory. It's a quick alternative to pwd when you want the value as a variable:
echo Current directory: $:
set backup = $:\backup # use it in a path
$$ — process ID of the shellA unique number identifying this cshw process. Mostly useful in scripts that need to create temp files with non-colliding names:
set tmpfile = C:\Temp\work-$$.txt # unique per shell instance
$argc, $argv, $1..$N, $resultWhen you write a procedure (Chapter 10), cshw makes its arguments available through a small set of special variables:
$argc — number of arguments passed in$argv — all arguments joined into a single space-separated string$1, $2, $3, ... — individual positional arguments$result — the value returned by the most recent procedure callYou won't use these much at the prompt; they earn their keep inside scripts. We'll meet them properly in Chapter 10.
$loopindexInside a loop block (Chapter 9), cshw maintains a counter variable. Its default name is $loopindex, but you can rename it with as:
loop 5 as i
echo Iteration $i
endloop
Again, forward reference to Chapter 9 for the full story.
Often you want a variable to hold the output of a command, not a literal string. cshw supports two syntactic forms for this; both work, pick whichever reads better in context.
set today = `say date`
set hostname = `say hostname`
set filecount = `dir /b | wc -l`
echo Today is $today on $hostname; $filecount files in the current folder.
The backticks (the ` character, usually on the same key as ~) run the enclosed command, capture its output, and substitute the result into the surrounding command.
$(...) formset today = $(say date)
set filecount = $(dir /b | wc -l)
Same idea, different syntax. The $(...) form is more readable when the substituted command itself contains backticks or other shell syntax, and it nests cleanly:
set summary = $(echo "Today: $(say date), files: $(dir /b | wc -l)")
TIP
In day-to-day shell use either form is fine. In scripts, the $(...) form tends to age better — it's easier to read, easier to nest, and won't trip up syntax highlighters. Stick to one form per script if you can; the inconsistency of mixing them is its own minor reading tax.
TRY IT
At the prompt, type:
set greeting = "It is $(say time) on $(say date) and the host is $(say hostname)"
echo $greeting
You just composed a sentence from three live command results.
When a variable holds a path, cshw lets you apply short modifiers directly to the expansion to slice it up — no basename/dirname/cut pipeline required. The syntax is $var:LETTER, and the letters are the same set tcsh has used for decades:
| Modifier | Meaning |
|---|---|
:t |
tail — keep only the last path component (basename) |
:h |
head — drop the last component (dirname) |
:r |
root — strip the final .ext |
:e |
extension — keep just the extension (no dot) |
:q |
quote — wrap in quotes (safe in re-evaluation) |
:x |
like :q, but split on whitespace into separate words |
:u |
upper — uppercase |
:l |
lower — lowercase |
:s/old/new/ |
substitute — replace the first old with new |
Modifiers chain — apply several at once by stacking them:
set p = "C:\Projects\cshw\src\main.cpp"
echo $p:t # main.cpp
echo $p:h # C:\Projects\cshw\src
echo $p:r # C:\Projects\cshw\src\main
echo $p:e # cpp
echo $p:t:r # main (basename, then strip ext)
echo $p:h:t # src (dirname, then basename — parent folder)
echo $p:s/main/app/ # C:\Projects\cshw\src\app.cpp
For walking a path component-by-component or transforming filenames in a foreach loop over *.cpp (rename .cpp to .cxx, say), modifiers turn what would be a three-line pipeline into a single token.
g and a — how many times to applyBy default a modifier applies once, to the first word. Two qualifiers change that, and they change different things:
| Qualifier | Meaning |
|---|---|
g |
apply once to each word |
a |
apply repeatedly to one word, until it stops changing |
set list = ( a.txt b.txt c.txt )
echo $list:r # a b.txt c.txt first word only
echo $list:gr # a b c every word
set deep = "a.b.c.txt"
echo $deep:r # a.b.c one extension stripped
echo $deep:ar # a keep stripping
g is the one you reach for most: it is what turns a modifier into something you can apply to a whole list in one token. a matters for values with repeated structure, like the multi-dot filename above.
TECHNICAL STUFF
The unit both qualifiers work on is the word, not the character. $w:gs/two/2/ on "one two three two" does not replace both occurrences, because that value is one word as far as the shell is concerned. This is tcsh's behaviour, verified against tcsh 6.24.13 rather than assumed — if you need every occurrence inside a single string, sed is the right tool.
@set always does string assignment. set x = 5 + 3 doesn't compute 8 — it stores the literal string "5 + 3". When you want actual math, use the @ command (the csh tradition for arithmetic assignment):
@ count = 0
@ count = $count + 1
@ total = 5 * 7
@ remainder = 17 % 4
@ pi = 3.14159
@ area = $pi * $r * $r
@ is a real expression evaluator: full C operator precedence with parentheses, all the arithmetic operators (+ - * / %), bit-shift and bitwise (<< >> & | ^ ~), comparison (< <= > >= == !=), logical (&& || !), compound assignment (+= -= *= /= %= <<= >>= &= |= ^=), and both prefix and postfix ++/--. Variables typed as floats stay as floats:
@ x = 1 + 2 * 3 # 7 (precedence respected)
@ y = (1 + 2) * 3 # 9 (parens override)
@ flags |= 0x10 # bitwise OR-assign
@ shifted = $n << 2 # left-shift
@ count += 1 # compound add
@ count++ # post-increment, same as += 1
@ writes its result into the named variable with the appropriate type — vartype n will report Integer for an integer result, Floating Point for a float result.
For functions you'd normally reach for awk or a separate language to compute, @ accepts a built-in library of math primitives organized into a few families:
sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanhlog (natural log; ln is an alias), log10, log2, expsqrt, cbrt, pow(x, y), hypot(x, y), root(x, n) for the nth rootfloor, ceil, round, trunc, fmodabs, sign, min(a, b), max(a, b)A few examples:
@ root = sqrt(2)
@ angle = sin($theta) + cos($theta)
@ y = pow($base, $exp)
@ fourth = root(256, 4) # 4
@ rounded = round($x)
@ clamped = max(0, min(100, $value))
The argument expressions are full sub-expressions; nesting and chaining work as you'd expect.
TIP
@ is the right tool for counters in loops. You'll write code like:
set total = 0
foreach n ($numbers)
@ total = $total + $n
end
echo Total: $total
in countless scripts. The pattern is small but you'll wear a groove into your keyboard with it.
TECHNICAL STUFF
For arbitrary-precision arithmetic — exact rationals, integer powers of arbitrary size, scientific calculations where 64-bit floats run out of room — cshw ships a real bc command (POSIX bc-compatible) and dc (RPN sibling). bc -x enables the exact rational + Power(rational, rational) tier, so bc -x answers sqrt(2)*sqrt(2) as exactly 2, not 1.9999...something. For everyday math, @ is what you want; for "I need 200 digits of precision," reach for bc.
An alias is a custom command name that expands to something else. They're great for:
The syntax is strict three-token: alias NAME VALUE. If the value contains spaces, quote it:
alias ll "dir /a"
alias la "dir /a /b"
alias .. "cd .."
alias proj "cd C:\Users\Me\Projects"
alias g grep
Now ll runs dir /a, .. is a quick parent-directory jump, proj warps you to your projects folder, and g is a two-character grep.
To see all defined aliases:
alias # no arguments -> display all
To remove one:
unalias ll
unalias -a # remove ALL aliases
rm /recycle habit (a callback from Chapter 4)In Chapter 4 we promised a useful aliasing trick: soft-delete by default while you're new to cshw. Here it is:
alias rm "rm /recycle"
Now every rm you type goes to the Recycle Bin. When you're comfortable enough that you trust your finger memory, drop the alias:
unalias rm
You're back to permanent-delete by default. For paranoid use, leave the alias in place forever — it's a per-shell-session cost of approximately zero.
Notice what that alias is doing: rm expands to rm /recycle, and the rm in the expansion is the built-in. That works because of a rule worth knowing explicitly.
proc → alias → built-in → PATHWhen you type a name, cshw looks for it in that order and runs the first thing it finds.
An alias beats a built-in. That's what makes alias rm "rm /recycle" and alias ls "ls -l" do anything at all — the whole point is to put your own spin on a command the shell already has.
The obvious worry is that alias rm "rm /recycle" should loop forever: rm expands to rm /recycle, whose first word is rm, which is an alias, which expands to... It doesn't, because of one rule borrowed from tcsh:
If the first word of an expansion is the alias being expanded, it is not expanded again.
So rm becomes rm /recycle exactly once, and that rm reaches the built-in. This is why the trick works rather than hanging your shell.
Aliases do chain when the names differ:
alias ll "ls -l"
alias lla "ll -a" # ll expands too, so this is ls -l -a
If you manage to build a genuine cycle — alias a b and alias b a — cshw notices and says Alias loop. instead of spinning.
WARNING
There is no backslash escape for aliases in cshw. In tcsh you can type \rm to bypass an alias for one command; here that does nothing special. To reach the real built-in past an alias, unalias it temporarily. To hide a built-in so something on your PATH runs instead, that's a different tool — see shadow in Chapter 23.
CHECK YOUR WORK
which rm tells you what a name will actually run, and where rm lists every match in the order above, first one winning. If an alias is in play, which says so.
REMEMBER
Aliases don't persist between sessions. When you close cshw, they vanish. To make them stick, put them in your startup script (.cshrc), which we cover at the end of this chapter.
Every csh variable is a list of words. A "regular" variable is simply a list with one word in it — set name = value and set name = (value) are the same thing, and both are subscriptable. An array is the same variable with more words:
set fruits = (apple banana cherry date)
That creates a four-element array. To access an element, use square-bracket subscript notation. Subscripts are 1-based, as they are in csh:
echo $fruits[1] # apple
echo $fruits[3] # cherry
Earlier printings of this chapter said the index was 0-based and offered $fruits[2] as "cherry". It is not: $fruits[2] is banana. $fruits[0] is out of range, as it is in tcsh — the shell says fruits: Subscript out of range. and does not run the command. For a while it was quietly accepted as [1], which was a bridge for those earlier printings; that bridge is gone, because a second numbering scheme is exactly the thing that made the off-by-one hard to see in the first place.
The same subscript works on a one-word variable, because a one-word variable is just a short list:
set greeting = hello
echo $greeting[1] # hello
echo $#greeting # 1
To get the number of words, use $#name:
echo $#fruits # 4
Subscripts count WORDS, never characters. For characters, use the substring form, which is separate syntax and — because it is borrowed from bash rather than csh — is 0-based:
set s = "hello world"
echo ${s:0:5} # hello
echo ${s:6} # world
echo $s[1] # hello world -- one word, quoted
Two numbering schemes in one paragraph is unfortunate, but both are correct in their own lineage, and bending either one to match the other would break scripts written against it. The rule that keeps them straight: square brackets count words from 1, colons count characters from 0.
array commandFor more elaborate array operations, the array command has subcommands:
array set NAME INDEX VALUE # assign one element
array get NAME INDEX # read one element (also sets $result)
array push NAME VALUE # append an element to the end
array size NAME # how many elements
array list NAME # print every element with its index
A working session:
set hosts = (web1 web2 web3)
array push hosts web4 # now (web1 web2 web3 web4)
array size hosts # 4
array list hosts # [1] = web1, [2] = web2, ...
array get hosts 1 # web1
array set and array get take the same 1-based index $name[n] does. There is one numbering scheme for arrays in this shell, and it starts at 1.
You can also create an array with the command directly, which is the same thing set name = (...) does:
array colors red green blue # declare and fill in one line
array colors # declared again: keeps what it holds
array empty_bucket # a name on its own: an empty array
declare -aIf you want to be explicit that a variable is an array (rather than relying on the lexer's parens trick), declare does it:
declare -a colors = (red green blue)
declare -a empty_list # empty array, ready to push into
The -a flag says "this is an indexed array." We'll see -A (associative array) next. The two differ only in case and mean different things, so declare -a -A name is refused rather than one of them quietly winning.
TECHNICAL STUFF
until recently both flags were read but never acted on. declare -a colors = (red green blue) produced a plain string, so $#colors was 1 and $colors[2] was empty. It was easy to miss because foreach c ($colors) still iterated three times — foreach splits the string itself — so the form looked right in the place it is most often used. Worth knowing if you have scripts written against the old behaviour: they will now get a real array, which is what they asked for.
Inside the parenthesized list of foreach (Chapter 9) or any other construct expecting a list, both $arr and ${arr} expand to the array's elements one-per-element:
foreach c ($colors) end # works
foreach c (${colors}) end # also works -- braces optional
The brace form is slightly safer when adjacent characters could otherwise look like part of the variable name (${arr}_suffix versus $arr_suffix). For arrays it's an exact synonym; reach for whichever reads more clearly in context.
TRY IT
Try this whole sequence:
set days = (Mon Tue Wed Thu Fri)
echo Today is $days[2]
echo Total: $#days
array push days Sat
array push days Sun
array list days
You should see a full week-list at the end.
A hash (also called an associative array) is like an array, but instead of integer indices, the elements are looked up by key — usually a string. Think of it as a tiny in-memory lookup table.
To declare an empty one:
declare -A config
To set entries, use the hash command's subcommands:
hash set config name MyApp
hash set config version 1.0
hash set config author Tarie
To read entries, use $name[key] syntax just like an array:
echo $config[name] # MyApp
echo $config[version] # 1.0
Or use the explicit hash subcommands:
hash get config name # MyApp
hash has config name # prints 1 if the key exists, 0 if not
hash keys config # name version author
hash list config # name=MyApp, version=1.0, ...
hash size config # 3
TIP
Hashes are how you build little structured data records in the shell. A common pattern: store config values in a hash, then read them throughout a script. It's the closest thing the shell offers to a struct or a dictionary, and once you start using them you'll wonder how you got by without them.
Arrays and hashes are deliberately small. The commands cover the cases shell scripts actually need; for richer data manipulation, you're better off in a real programming language or one of the heavyweight text tools (awk, sed). Four current limits, each with a workaround.
pop, shift, or splice on arraysThe array command offers set, get, push, size, and list. There's no built-in way to remove an element from the front, back, or middle. The workaround is filter into a new array — build the array you want rather than mutate the one you have:
# Build a new array, dropping any element matching "obsolete":
declare -a keepers
foreach item ($original)
if ("$item" != "obsolete") then
array push keepers "$item"
endif
end
This is the standard immutable-collections pattern: don't try to edit the array, just construct the version you want and use that.
hash delete (or remove)The hash command sets and reads entries but doesn't remove them. The standard workaround is a sentinel value — pick a string you'd never use as a real value, and treat that as "deleted":
hash set config debug_mode "<unset>"
hash get config debug_mode
if ("$result" != "<unset>") then
echo "debug_mode is: $result"
endif
It's not elegant, but it's enough for the use cases hashes typically serve in shell scripts (configuration, counters, lookup tables).
A hash value is a string. An array element is a string. You can't store an array inside a hash, or a hash inside an array. Two common workarounds:
id → (name, email, role), keep three arrays — names, emails, roles — and use the same index across all three.(user, field) pairs, just join them with a separator: hash set userdata "alice.email" "alice@example.com", then parse the key back out when needed.Both patterns are how the language itself stays small; the price you pay is on the reader's side rather than the implementation's.
hash keys and hash list walk the hash in sorted-key order (lexicographic for strings). That's a real guarantee — same keys always come out in the same order — but it's not the order you inserted them. If you need to iterate in insertion order, keep a parallel array of keys:
declare -a key_order
hash set config name "MyApp"
array push key_order name
hash set config version "1.0"
array push key_order version
hash set config author "Tarie"
array push key_order author
foreach k ($key_order)
hash get config $k
echo "$k = $result"
end
The array remembers insertion order; the hash is just a fast lookup.
REMEMBER
cshw's collections are shaped for shell problems: a list of files, a small table of settings, a counter per category. The moment your data wants to be deeply nested, mutated in place, or indexed by complex keys, you've outgrown shell scripting — and that's a good sign. Reach for awk when records-and-fields fits; reach for genai (Chapter 17) when the data needs interpretation more than processing; reach for a real programming language when neither of those is right. The shell stays a shell. Knowing when to step outside it is part of using it well.
readonly, local, declareA handful of commands modify how a variable behaves.
readonly — variables that can't be changedSometimes you want to set a constant — a value that shouldn't change for the rest of the session:
readonly PI = 3.14159
set PI = 4 # error: PI is readonly
Or using declare -r:
declare -r MAX_RETRIES = 5
Both make the variable immutable. Useful for configuration constants and for scripts that take command-line parameters they don't want to accidentally clobber.
To see every readonly variable in your shell:
readonly # no args -> list them all
local — procedure scope onlyInside a procedure (Chapter 10), you sometimes want a variable that exists only for the duration of the procedure call and doesn't leak out to the caller's scope. That's local:
proc compute_things
local temp = 0
local result = 0
@ temp = $1 * 2
@ result = $temp + 1
return $result
endproc
temp and result exist only inside compute_things. After the procedure returns, they're gone.
local only works inside a procedure — at the top level, it'll refuse:
local x = 5 # error: local can only be used inside a procedure
We'll come back to this in Chapter 10 where it actually makes sense.
declare — the flag aggregatordeclare is the multi-tool that combines the above. The flags:
-r — make readonly-a — declare as indexed array-A — declare as associative array (hash)You can combine them:
declare -r -a constants = (alpha beta gamma)
declare -r PI = 3.14159
declare -A settings
If you only ever remember one of readonly, array, hash, and declare, declare is probably the right pick — it covers all three.
.cshrc Startup FileSo far everything you've set up — variables, aliases, environment tweaks — exists only inside your current shell session. The moment you close the window, it's gone. To make customizations stick, cshw reads a startup file every time it launches an interactive shell.
The file location, in order of preference:
%USERPROFILE%\.cshrc (the Unix-flavored name, in your home directory)%APPDATA%\cshw\cshwrc (the Windows-flavored fallback, if the first doesn't exist)If either exists, cshw runs it before the prompt appears. So you can put your aliases, environment tweaks, and any other initialization there:
# Example .cshrc
# Aliases I always want
alias ll "dir /a"
alias la "dir /a /b"
alias .. "cd .."
alias ... "cd ..\.."
# Soft-delete by default for a while
alias rm "rm /recycle"
# My environment
setenv MY_PROJECTS "C:\Users\Me\Projects"
setenv PATH "$MY_PROJECTS\bin;$PATH"
# Friendly prompt
prompt "$J$S$P$G "
The syntax is just regular cshw commands, one per line, the same way you'd type them at the prompt. Comments start with #.
.login and .logout.cshrc runs for every shell — including ones you didn't start on purpose. A backtick like `date` is a shell. So is a script. So is each stage of a pipeline. That's fine for aliases and variables, which are cheap, but it's the wrong home for anything slow or anything you only want to happen once.
That's what .login is for. Start cshw with -l and it becomes a login shell — the session's first — and reads two more files:
| file | when |
|---|---|
%USERPROFILE%\.cshrc |
every interactive shell |
%USERPROFILE%\.login |
login shells only, after .cshrc |
%USERPROFILE%\.logout |
login shells only, on the way out |
# .login — once, at the start of the session
echo "Welcome back, $USERNAME."
if (-e "$HOME\notes\today.md") cat "$HOME\notes\today.md"
# .logout — once, on the way out
echo "Session ended `date`" >> "$HOME\.sessions.log"
Inside a file that both kinds of shell read, $?loginsh tells you which you're in:
if ($?loginsh) then
# only in the session's first shell
endif
REMEMBER
cshw is a login shell because you told it to be, not because it worked it out. On Unix the login program starts your shell with a special marker; nothing on Windows does that, so -l is how you say so. The Start-menu shortcut passes it; a cshw you start from inside another cshw doesn't — which is exactly the line these files are meant to draw.
-l has to come before -c, because everything after -c is the command.
logout ends a login shell, running .logout on the way. In any other shell it tells you Not login shell. and stays put — that's the difference between it and exit, which works anywhere.
TIP
Create your .cshrc once and you'll wonder how you ever lived without it. It's the difference between "this is a tool I use" and "this is my tool." Drop your aliases, your favorite environment, your custom prompt — anything you want to wake up to every morning — and cshw will set it all up for you the moment a new shell opens.
TRY IT
Open a text editor and create %USERPROFILE%\.cshrc. Put in:
alias ll "dir /a"
echo "Welcome back, $USERNAME!"
Close cshw and open it again. You'll see the welcome message, and ll will work as a shortcut for dir /a.
source — re-run the startup file (or any script) without restartingIf you edit your .cshrc and want the changes without closing and reopening the shell, run source:
source ~/.cshrc
source reads and executes the named file in the current shell, so any variables, aliases, or settings it defines stick around. The single-dot form is an alias that does the same thing:
. ~/.cshrc
This is also handy for splitting your customizations across multiple files — one for aliases, one for environment, one for prompt setup — and sourcing them all from your .cshrc. We'll see more of source and how scripts work in Chapter 8.
You can now define variables, manage the environment, build shortcuts, and make your customizations persistent. That's enough to start treating cshw as your shell rather than a generic one.
The next chapter — Chapter 6 — covers pipes and redirection, which is where these little tools we've been collecting really start to compose into something more than the sum of their parts. We'll wire commands together, route output to files, and split streams. You'll be writing one-liners that do real work by the end.
If you got particularly far in this chapter — say, you have a working .cshrc with a handful of aliases — you've already started the shift from "user" to "power user." That's the path the rest of the book follows.