←  cshw: The C Shell for Windows

Chapter 9

Control Flow: Branches, Loops, and Choices

In This Chapter

A linear script — one that runs top to bottom with no decisions and no repetition — gets you surprisingly far. But every interesting program asks "what if?" or "for each of these…" at some point. This is the chapter that puts those questions on the table.

The constructs here are the core programming vocabulary of cshw. Once you have them, the difference between a "script" and a "program" mostly comes down to ambition, not capability.


if / else / endif — Making Decisions

The simplest form is a single-branch if:

if ($x > 5) then
    echo "x is bigger than 5"
endif

The four pieces:

REMEMBER

Keywords are lowercase, and only lowercase. if, then, endif, foreach, end, while, switch, endsw, proc, endproc — all of them, always. If is not a conditional and ENDIF closes nothing; cshw reads them as ordinary command names, which is what csh and tcsh do too.

This is the one place cshw is stricter about case than the rest of Windows. Command names aren't: DIR, Dir and dir all run the same thing, because that's how Windows resolves programs. The language's own keywords are a different matter — if If opened a block, then every line of English prose starting with "If" would too, and csh scripts traditionally end with a section of plain help text. One of them would leave a block open and the whole file would fail to parse over a sentence.

Everything between then and endif runs only when the condition is true. With more than one statement in the body, just put them on consecutive lines:

if ($age >= 18) then
    echo "Welcome."
    set is_adult = 1
    log_entry "$name granted access"
endif

Adding an else branch

When you need a fallback, add else:

if ($score >= 60) then
    echo "Passed."
else
    echo "Failed."
endif

If the condition is true, the then block runs. If it's false, the else block runs. One or the other — never both.

else if chains

For more than two branches, chain with else if:

if ($grade >= 90) then
    set letter = "A"
else if ($grade >= 80) then
    set letter = "B"
else if ($grade >= 70) then
    set letter = "C"
else if ($grade >= 60) then
    set letter = "D"
else
    set letter = "F"
endif

The chain stops at the first true branch. If none match and there's an else, that runs. Only one endif closes the whole chain — else if doesn't need its own.

TIP

When the chain gets long, consider whether switch (later in this chapter) reads more cleanly. if/else if is right when each branch has a different kind of condition; switch is right when you're comparing one expression against several values.

REMEMBER

endif closes if. end closes while and foreach. endloop closes loop. endsw closes switch. They're each named after the keyword they're closing — a small kindness that pays off when you're nesting structures.

TRY IT

Save this as weather.cshw and run it with different numbers:

# weather.cshw - tells you what to wear
set temp = $1
if ($temp < 0) then
    echo "Coat, hat, and gloves."
else if ($temp < 15) then
    echo "Jacket."
else if ($temp < 25) then
    echo "Sweater."
else
    echo "T-shirt and shorts."
endif

Run weather.cshw -10, then weather.cshw 20, then weather.cshw 30. Each branch fires for the right temperature.


The Condition Language

What goes inside the parentheses of an if (or while, or any other place that takes a condition) is a small expression language. Knowing it well is most of what makes scripts reliable.

Comparison operators

For comparing two values:

Operator Meaning Compares
== equal text
!= not equal text
< less than numbers
> greater than numbers
<= less than or equal numbers
>= greater than or equal numbers
if ($x == 5) then ...
if ("$name" != "admin") then ...
if ($count >= $max) then ...

That third column is the whole type system, and it is worth reading twice: == and != compare text; the four ordering operators compare numbers. This is csh's rule, inherited unchanged, and it is what lets 5 < 10 be true while "5" == "05" is false.

The consequence that surprises people is that equal-looking numbers can be unequal strings:

if ( 5 == 05 )       # FALSE -- "5" and "05" are different text
if ( 10 == 010 )     # FALSE
if ( 007 == 7 )      # FALSE
if ( 5 < 10 )        # true  -- ordering is numeric

The rule earns its keep the moment your values are not really numbers. Version fragments, zero-padded dates, account ids, and error codes are all written with digits and none of them are quantities. A shell that "helpfully" compared them as numbers would tell you 1.0 and 1.00 are the same version, and that customer 007 and customer 7 are the same customer.

Saying you meant the number: num, @ and str

When you do want digits read as a quantity, put a cast on either operand. It sets the comparison for the whole expression:

set month = 1

if ( num $month == "01" )    # true  -- 1 equals 1
if ( @   $month == "01" )    # true  -- same thing
if ( str $month == "01" )    # false -- text, said out loud

All three are one keyword followed by the operand it applies to. num and str name what they do. @ is there because @ is already cshw's arithmetic tier (Chapter 8), so "read this the way @ would" is a thing you already know how to say.

A numeric cast compares as a float when either side has a fraction or an exponent, and as a 64-bit integer otherwise — so large integers keep the precision a float would lose:

if ( @ 5 == 5.0 )      # true
if ( @ 0.5 == 0.4 )    # false -- not truncated to 0 == 0

str also works on the ordering operators, where it makes them alphabetical:

if ( str "10" < str "9" )    # true  -- "1" sorts before "9"
if ( "10" < "9" )            # false -- numeric, as usual

A cast is only a cast when there is something after it to cast. num and str are ordinary words the rest of the time, so nothing you already wrote changes meaning:

if ( num == 5 )              # compares the WORD "num" with 5
if ( numeric == numeric )    # a longer word is left alone
set num = 5
if ( $num == 5 )             # a variable named num reads normally

PORTING NOTE

tcsh has no cast keywords; num $x == "01" is a cshw extension. A script using them will not run under tcsh, so if portability matters, write the comparison the long way (if ( $x == 1 || $x == 01 )) or normalise the value before you test it. The default behaviour of == matches tcsh exactly, so a script that avoids the casts ports cleanly.

TECHNICAL STUFF

Quoting matters when the value might be empty or contain spaces. if ("$name" == "admin") is safer than if ($name == admin) because if $name is empty, the unquoted version becomes if ( == admin) — a syntax error. The quoted version becomes if ("" == "admin") — false, which is what you want. Get into the habit of quoting string variables in conditions.

Truthy values

A condition that's just $var (no comparison) is true when the variable has a "truthy" value:

So:

set flag = "yes"
if ($flag) then ...        # true

set flag = ""
if ($flag) then ...        # false

set flag = 0
if ($flag) then ...        # false

set flag = 42
if ($flag) then ...        # true

This is the standard "is this variable set to anything useful?" check.

Logical operators

For combining conditions:

Operator Meaning
! NOT (unary)
&& AND
|| OR
if ($x > 0 && $x < 100) then ...                   # both must be true
if ($mode == "fast" || $mode == "turbo") then ...  # either is enough
if (! $logged_in) then ...                         # NOT logged in

Parentheses group sub-expressions:

if (($x > 0 && $x < 10) || $x == 100) then ...

TIP

&& and || short-circuit. If the left side of && is false, the right side is never evaluated. If the left side of || is true, the right side is never evaluated. That matters when the right side has a side effect or might fail — put the cheaper or safer check on the left.

File-test operators

For asking the filesystem questions without spawning a separate command:

Operator Meaning
-e PATH exists (file or directory)
-f PATH exists AND is a regular file
-d PATH exists AND is a directory
if (-e "config.ini") then
    source config.ini
endif

if (-d "$backup_root") then
    echo "Backup folder ready."
else
    mkdir -p "$backup_root"
endif

if (! -f "$1") then
    echo "ERROR: $1 is not a regular file."
    exit 1
endif

These are much faster than running find or dir and checking output — and they read more naturally as conditions.

TRY IT

At the prompt (where if works too, inside a parenthesized expression):

if (-d "C:\Windows") then
    echo "Windows exists. Phew."
endif

while Loops — Repeat While True

A while loop runs its body over and over until the condition becomes false:

set i = 0
while ($i < 5)
    echo "iteration $i"
    @ i = $i + 1
end

Output:

iteration 0
iteration 1
iteration 2
iteration 3
iteration 4

The four pieces:

The condition is checked before each iteration, including the first. If it's false to start with, the body never runs.

WARNING

Make sure something inside the loop body changes the condition, or you've got an infinite loop. The @ i = $i + 1 (or equivalently @ i++) above is what eventually makes $i < 5 false. Without it, $i stays at 0 forever and the loop runs until you press Ctrl+C.

A more realistic example

while is the right choice when you don't know in advance how many iterations you'll need. Reading lines from a file, retrying until success, processing a work queue — anything with a "keep going until…" feel:

# Retry up to 5 times
set attempts = 0
set success = 0
while ($attempts < 5 && ! $success)
    @ attempts = $attempts + 1
    echo "Attempt $attempts..."
    do_the_thing
    if ($? == 0) then
        set success = 1
    endif
end

if ($success) then
    echo "Worked on attempt $attempts."
else
    echo "Gave up after 5 tries."
endif

do / while — Test at the Bottom

Sometimes you want the body to run at least once before the condition is checked. That's do/while:

do
    echo "Hello"
    @ count = $count + 1
while ($count < 3)

The body runs unconditionally the first time. After it finishes, the condition is checked; if true, the body runs again; if false, the loop ends.

do/while doesn't have a separate end keyword — the while line at the bottom serves double duty as "end of body, here's the condition to retest."

The classic use case: prompting the user until they give valid input. You always need to ask at least once, so the test-at-the-bottom pattern fits:

do
    echo -n "Enter Y to continue, N to quit: "
    set answer = $(read_input)            # hypothetical input command
while ("$answer" != "Y" && "$answer" != "N")

for — A Three-Part Loop

C, Java, JavaScript, and most curly-brace languages have a for (init; cond; incr) form for loops where you know the shape of the iteration: a counter that starts somewhere, runs while a condition holds, and advances each pass. cshw has the same construct:

for i = 0; $i < 5; i++
    echo "iteration $i"
endfor

Three pieces between for and the newline:

A few notes on that example:

Examples

Custom step:

for i = 0; $i < 20; @ i = $i + 2
    echo $i
endfor

Counting down:

for n = 10; $n > 0; n--
    echo $n
endfor
echo "Blast off!"

Parens around the header are accepted if your eye prefers them:

for (i = 0; $i < 5; i++)
    echo $i
endfor

Empty parts are tolerated. for ; $i < 5; i++ starts from whatever $i happens to be already; for i = 0; $i < 5; has no incr (so the body had better change something or you've got an infinite loop).

TIP

for and loop look similar at a glance but they're for different jobs. loop $N reads $N once at the top and runs that many times — mutating $N in the body has no effect on iteration count. for i = 0; $i < $N; i++ re-evaluates $N every iteration, so if the body changes it (or anything else the condition references), the loop notices immediately. Pick loop when the count is fixed at entry; pick for when the loop variable, the limit, or both can change during iteration.

TECHNICAL STUFF

break exits the for loop immediately (no final incr). continue skips the rest of the body but still runs the incr step before the next condition check — matching the C convention. That's the bit most C programmers expect and most shell scripters get burned by, so it's worth a quick mental check whenever you reach for continue inside a for.

TRY IT

Save and run:

for i = 0; $i < 5; i++
    echo "i=$i"
    if ($i == 2) then
        continue
    endif
    echo "  body at $i"
endfor

You'll see five "i=N" lines and four "body at N" lines — the body at i=2 got skipped but the incr still fired, so the loop didn't get stuck.


loop — Repeat Exactly N Times

When you know up front how many iterations you want, loop is more readable than a hand-rolled while:

loop 10
    echo "ping"
endloop

That prints "ping" ten times. Compare with the while equivalent:

set i = 0
while ($i < 10)
    echo "ping"
    @ i = $i + 1
end

loop is shorter and obviously bounded — no risk of an infinite loop.

The $loopindex variable

Inside a loop body, cshw maintains an automatic counter named $loopindex. It is one-based — it counts 1 through N, matching array subscripts:

loop 5
    echo "Iteration $loopindex"
endloop

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

REMEMBER

Earlier printings said $loopindex was zero-based, and it was. It changed so that the whole language counts from one: arrays are 1-based, $argv[1] is the first argument, and loop $#items as i now lines up with $items[$i] the way it obviously reads. If you have a script that relied on the old numbering, the counter is the thing to check.

If you want a different starting point, that is what for and while are for — there you write the bounds, and nothing is baked in:

for i = 0; $i < 5; i++      # count from zero, if that is what you need
    echo $i
endfor

Renaming the index with as

If you want the index variable to have a more meaningful name, use as:

loop 5 as step
    echo "Step $step of 5"
endloop

Output:

Step 0 of 5
Step 1 of 5
Step 2 of 5
Step 3 of 5
Step 4 of 5

The as NAME clause is purely a rename — same behavior, different variable name. Useful when you have nested loops and need to tell the indices apart:

loop 3 as row
    loop 3 as col
        echo "($row, $col)"
    endloop
endloop

A variable count

The N in loop N doesn't have to be a literal — it can be a variable:

set repeat_count = 7
loop $repeat_count
    do_the_thing
endloop

REMEMBER

loop closes with endloop, not end. The same closer-pair convention applies: each open keyword has its own matching close keyword.


foreach — Iterate Over a List

Where loop runs N times, foreach runs once per item in a list:

foreach color (red green blue)
    echo "Color: $color"
end

Output:

Color: red
Color: green
Color: blue

The shape: foreach VARNAME (list of items) ... end. On each iteration, $VARNAME is set to the current item.

Iterating over a variable's value

If a variable holds a multi-word value, you can use it as the list:

set cities = (Tokyo Paris Boston)
foreach city ($cities)
    echo "Visiting $city"
end

File globs in the list

This is where foreach gets fun. Glob patterns expand into the list — so you can iterate over files:

foreach file (*.txt)
    echo "Processing $file..."
    wc -l "$file"
end

Or process every C++ file in a folder tree:

foreach src (src\*.cpp src\**\*.cpp)
    echo "Compiling $src"
    cl /c "$src"
end

Empty lists

If the list expands to nothing — for example, a glob with no matches — foreach quietly does zero iterations:

foreach file (*.nonexistent)
    echo "Found $file"
end
# Nothing prints. No error.

That's usually what you want.

TIP

foreach file (*.cshw) is the cleanest way to "do something to every script in this folder." Combined with if, you can filter further: skip files whose names start with _, only process ones modified in the last 24 hours, etc.

TRY IT

Run this at the prompt to count lines in every .txt file in your current folder:

foreach f (*.txt)
    echo -n "$f: "
    wc -l "$f"
end

If you don't have any .txt files here, the loop body never runs and you get no output. That's the empty-list behavior at work.


switch / case — Multi-Way Branches

When you want to compare one value against many possibilities, switch is cleaner than a long if/else if chain:

switch ($command)
    case "start":
        start_service
        breaksw
    case "stop":
        stop_service
        breaksw
    case "restart":
        stop_service
        start_service
        breaksw
    default:
        echo "Unknown command: $command"
        breaksw
endsw

The pieces:

csh-style pattern matching

Each case's pattern isn't just a literal — it's a glob pattern, the same way *.txt works in filenames:

switch ($filename)
    case "*.txt":
        echo "Text file"
        breaksw
    case "*.cpp":
    case "*.h":
        echo "C++ source"
        breaksw
    case "*.exe":
        echo "Executable"
        breaksw
    default:
        echo "Other"
        breaksw
endsw

The glob characters that work in case patterns:

Fall-through (stacking cases)

If a case has no breaksw, execution falls through into the next case. That's why the *.cpp and *.h example above works — both patterns end up running the same body because the first case ("*.cpp":) has no body and no breaksw, so it falls through into the "*.h": case.

The deliberate, idiomatic use is to share a single action across multiple cases:

switch ($day)
    case "Mon":
    case "Tue":
    case "Wed":
    case "Thu":
    case "Fri":
        set kind = "weekday"
        breaksw
    case "Sat":
    case "Sun":
        set kind = "weekend"
        breaksw
endsw

WARNING

Forgetting breaksw is the classic switch bug — accidental fall-through. If you have case "start": start_service with no breaksw after start_service, execution will fall into whatever case comes next. That's usually not what you want. Put a breaksw after every case unless you're deliberately stacking, and stacked cases should have empty bodies (with a comment if it's not obvious why).

REMEMBER

break exits loops. breaksw exits switches. They're named differently on purpose: a break inside a switch nested inside a loop would exit the loop, not the switch. Mixing them up is easy and produces baffling behavior.


break and continue — Escape Hatches

Inside a loop (while, do/while, loop, or foreach), two keywords let you change the normal flow:

break — give up early

foreach file (*.log)
    if (-d "$file") then
        echo "Stopping: $file is a directory, that's weird."
        break
    endif
    process_log "$file"
end

The break bails out of the loop the moment something unexpected appears, without finishing the rest of the files.

continue — skip this one, keep going

foreach file (*)
    if (-d "$file") then
        continue          # skip directories, only process files
    endif
    process_file "$file"
end

continue says "this iteration is done; move on to the next item." The loop keeps running; only the rest of this iteration is skipped.

A combined example

A while loop processing items from a queue, skipping invalid ones and stopping if something catastrophic happens:

while ($queue_has_items)
    set item = $(queue_pop)
    if ("$item" == "") then
        continue          # empty item, skip
    endif
    if ("$item" == "STOP") then
        break             # done, stop the loop entirely
    endif
    process_item "$item"
end

TECHNICAL STUFF

break and continue only affect the innermost enclosing loop. In nested loops, they don't reach the outer one. If you really need to break out of an outer loop from inside an inner one, you'd typically set a flag and check it after the inner loop ends — or, in extremis, use goto to a label past the outer loop. (Read on for goto's appropriate cautionary speech.)


return — Briefly

return exits the current procedure and optionally sets a return value. Since procedures are the subject of Chapter 10, we'll defer the full discussion there. For now:


goto and Labels — The Tool of Last Resort

cshw supports goto for unconditional jumps within a script. A label is an identifier followed by a colon, on a line by itself:

echo "Before"
goto skip
echo "This is skipped"
skip:
echo "After"

Output:

Before
After

Labels and gotos find each other across the entire script (or procedure). You can jump forward or backward.

When to use goto

The honest answer is "almost never." The structured constructs we've already covered — if, while, foreach, switch, break, continue — handle nearly every flow-control need in a way that's easier to read and easier to maintain. goto makes code's flow harder to follow because the reader has to scan forward and backward to find where execution continues.

The narrow cases where goto is defensible:

  1. Breaking out of deeply nested loops. break only exits one level. If you're three loops deep and need to abort the whole thing, a goto past_all_loops: is sometimes clearer than three flag variables.
  2. Error handlers that need to be reached from many places. Some scripts have a single cleanup block they want to jump to from any of a dozen possible failure points. goto cleanup: from each is genuinely simpler than restructuring.
  3. Interrupt handlers via onintr. onintr LABEL tells the shell to goto LABEL when Ctrl+C interrupts a running script — a clean way to reach a cleanup block on interrupt instead of letting the script die mid-operation. (onintr - ignores interrupts; a bare onintr restores the default. The jump happens at the next statement boundary.)

For everything else, prefer structured constructs. If a procedure body is so tangled that goto looks attractive, the tangle is the real problem.

WARNING

Code with lots of gotos is harder to read, harder to debug, and harder to change without breaking. It's a tool that exists for the corner cases above; it's not a normal control-flow mechanism. When in doubt, refactor.


Putting It Together: A Practical Example

Here's a real script that exercises most of this chapter — a log-file cleaner that scans a folder, archives old logs, and reports what it did.

# cleanup_logs.cshw — archive logs older than N days
#
# Usage:  cleanup_logs.cshw <log-dir> [days]
# Example: cleanup_logs.cshw C:\Logs 30

# --- Argument validation ---

if ($argc < 1) then
    echo "Usage: cleanup_logs.cshw <log-dir> [days]"
    exit 1
endif

set log_dir = $1
set days = $2
if ("$days" == "") then
    set days = 30
endif

if (! -d "$log_dir") then
    echo "ERROR: $log_dir is not a directory."
    exit 1
endif

# --- Set up archive folder ---

set archive_dir = "$log_dir\archive"
if (! -d "$archive_dir") then
    mkdir "$archive_dir"
endif

# --- Process each log file ---

set archived = 0
set skipped = 0

foreach log ($log_dir\*.log)
    # Skip files already in archive
    switch ($log)
        case "*\archive\*":
            continue
            breaksw
        default:
            breaksw
    endsw

    # Check age (find -mtime returns true for "modified MORE than N days ago")
    set is_old = $(find "$log" -mtime +$days -type f 2>nul | wc -l)

    if ($is_old > 0) then
        echo "Archiving: $log"
        mv "$log" "$archive_dir"
        @ archived = $archived + 1
    else
        @ skipped = $skipped + 1
    endif
end

# --- Report ---

echo ""
echo "Done. Archived $archived files, kept $skipped."

if ($archived == 0) then
    exit 0
else
    exit 0
endif

In about thirty lines, this script uses:

That's the entire chapter, condensed into one working tool. Save it, run it on a folder full of logs, and watch the cleanup happen.

TRY IT

Type the script in (or copy from the markdown), save it as cleanup_logs.cshw, and run it on a directory you don't care about deeply. Try it with a days value of 0 to archive everything; try with 999999 to archive nothing. Watch how the counts adjust.


Onward

You now have the complete control-flow toolkit. Linear scripts are behind you — your scripts can make decisions, loop, and react to conditions just like any real program.

The one big piece left is organization: how to package up reusable behavior so a complicated script doesn't become a 500-line spaghetti file. That's Chapter 10 — procedures and libraries. We'll see how to define named, parameterized blocks of code (procedures), how to load shared procedure files at startup, and how to build a personal library of helpers you can reuse across every script you write.

By the end of Chapter 10, the foundation is complete and Part III is in the rearview mirror. After that, Part IV opens the trunk and shows off what makes cshw special — jobs, coroutines, networking, AI, plugin DLLs.

If you've made it this far without nodding off: well done. The most demanding chapter of the book is behind you. From here on out, it's all variations on the themes you already know.