Chapter 11
In This Chapter
foreach and loophash keysChapter 5 introduced arrays and hashes as data containers. This chapter is about actually using them — putting data in, getting it out, walking it, transforming it. After scripts, control flow, and procedures, collections are the last big piece of the scripting toolkit. By the end of this chapter you can build the kind of small data-processing scripts that turn cshw from "a shell" into "a small ETL workbench."
Just enough to anchor what follows:
set fruits = (apple banana cherry) or array fruits apple banana cherry. Read with $fruits[1]. Length is $#fruits. Append with array push fruits date. Subcommands: array set, array get, array push, array size, array list, all of which take 1-based indices too.declare -A config. Set with hash set config name MyApp. Read with $config[name] or hash get config name. Subcommands: hash set, hash get, hash keys, hash list, hash size.If anything above is unfamiliar, flip back to Chapter 5's Arrays and Hashes sections before continuing.
We saw foreach in Chapter 9 with literal lists. The same construct works over arrays:
set fruits = (apple banana cherry date)
foreach f ($fruits)
echo "I like $f"
end
Output:
I like apple
I like banana
I like cherry
I like date
The $fruits inside the () expands to the array's elements, and foreach walks them one at a time. This is the workhorse for "do something with each item."
If you need the index as well as the value — for printing line numbers, modifying specific positions, or pairing two arrays element-by-element — use loop with $#array as the count:
set fruits = (apple banana cherry date)
loop $#fruits as i
echo "[$i] $fruits[$i]"
endloop
Output:
[1] apple
[2] banana
[3] cherry
[4] date
That lines up because loop's counter is one-based, exactly like array subscripts. loop $#fruits as i runs i from 1 to 4, and $fruits[$i] is the matching element every time — no adjustment, no off-by-one.
The same thing written by hand, when you want the counter to do something less ordinary:
set i = 1
while ($i <= $#fruits)
echo "[$i] $fruits[$i]"
@ i++
end
TIP
loop is for "N times"; while and for are for when you want to control the bounds. for i = 0; $i < $#fruits; i++ counts from zero if that is genuinely what you need — the difference is that with for you wrote the zero yourself, so it can't surprise you.
The $#fruits evaluates to the array length, and loop ... as i gives you a counter to index into the array.
TIP
Reach for foreach when you just need each value. Reach for loop $#arr as i when you need the index too. The first form is shorter and clearer when it fits; the second is there when you need it.
A common pattern when you have two arrays that should be processed pair-by-pair (parallel arrays):
set names = (alice bob charlie)
set scores = (87 92 78)
loop $#names as i
echo "$names[$i]: $scores[$i]"
end
Output:
alice: 87
bob: 92
charlie: 78
Parallel arrays are a common pattern when a hash isn't quite right — for example, when you want preserved insertion order, or when the relationship isn't a clean key-to-value mapping.
TRY IT
Save this and run it:
set days = (Mon Tue Wed Thu Fri)
set tasks = ("write code" "review PRs" "team meeting" "1:1s" "deploy")
loop $#days as i
echo "$days[$i]: $tasks[$i]"
endloop
Most real arrays don't come from a set arr = (...) literal — they're built up at runtime, one element at a time, by array push.
declare -a powers_of_two
loop 10 as i
@ p = 1
loop $i
@ p = $p * 2
endloop
array push powers_of_two $p
endloop
array list powers_of_two
Output:
[1] = 1
[2] = 2
[3] = 4
[4] = 8
[5] = 16
[6] = 32
[6] = 64
[7] = 128
[8] = 256
[9] = 512
The inner loop computes a value; the outer loop's array push accumulates it.
A frequent pattern: take an existing collection and produce a new one containing only the elements that match some criterion.
set numbers = (3 17 8 22 1 14 9 30)
declare -a big_ones
foreach n ($numbers)
if ($n > 10) then
array push big_ones $n
endif
end
array list big_ones
# [1] = 17
# [2] = 22
# [3] = 14
# [4] = 30
We didn't mutate $numbers — we built a new array, $big_ones, containing only the values that passed the test. Filtering is almost always done this way: leave the input alone, build a new output. (cshw has no built-in "remove this element" operation on arrays — see the Limits section at the end.)
Mirror image of filtering: apply a transformation to each element and produce a new array of results.
set words = (hello world cshw rocks)
declare -a uppercased
foreach w ($words)
set up = $(echo $w | tr a-z A-Z)
array push uppercased $up
end
array list uppercased
# [1] = HELLO
# [2] = WORLD
# [3] = CSHW
# [4] = ROCKS
The pattern is identical to filtering — foreach over input, array push to output — but the body transforms each element rather than choosing whether to keep it.
When you want one answer out of many inputs — a sum, a max, a count of matching items — reduce over the array:
set values = (4 7 2 9 11 5 8)
@ total = 0
@ count = 0
@ maxval = 0
foreach v ($values)
@ total = $total + $v
@ count = $count + 1
if ($v > $maxval) then
@ maxval = $v
endif
end
@ average = $total / $count
echo "Sum: $total, Count: $count, Average: $average, Max: $maxval"
Output:
Sum: 46, Count: 7, Average: 6, Max: 11
The body of the loop updates one or more accumulator variables, and after the loop you read the final values. Most "compute a summary statistic from a list" tasks boil down to this pattern.
REMEMBER
Filtering, mapping, and reducing aren't built-in commands — they're patterns you build with foreach + array push (filter/map) or foreach + accumulator (reduce). Once you've seen them once, you'll recognize them all over real scripts.
A killer use of arrays is loading a file's lines (or some command's output) into a collection you can then index, iterate, and process.
type (or cat, your choice) dumps a file's lines; pipe them into a procedure that pushes each line onto an array:
declare -a lines
foreach line (`type list.txt`)
array push lines $line
end
echo "Read $#lines lines."
echo "First line: $lines[1]"
echo "Last line: $lines[$#lines]"
The last element is $lines[$#lines], not $#lines - 1: subscripts count from 1, so the count and the last index are the same number. Arithmetic inside a subscript does not work either way — cshw's subscript expects a single integer — so if you need a computed index, compute it first:
@ second_to_last = $#lines - 1
echo "Second to last: $lines[$second_to_last]"
Same pattern with any command:
declare -a cpp_files
foreach f (`find . -name "*.cpp"`)
array push cpp_files $f
end
echo "Found $#cpp_files .cpp files."
Once they're in an array you can iterate, filter, count, or random-access them however you like.
TECHNICAL STUFF
The backtick form treats whitespace as a separator. For lines that contain spaces ("my photos.jpg" etc.), the file-line approach above will break each space-containing line into multiple array entries. For paths or other space-bearing data, a more robust loader is to read line-by-line with a sed-or-awk pipeline that emits one record per line and a delimiter that won't appear in the data. Or just store the data in a format that doesn't have spaces (TSV, etc.). This is a real limitation of shell-level string handling, not specific to cshw.
Hashes don't have a numeric "first to last" order — they're key-value lookups. To walk one, ask for its keys:
declare -A config
hash set config host example.com
hash set config port 8080
hash set config timeout 30
foreach key (`hash keys config`)
set value = $(hash get config $key)
echo "$key = $value"
end
Output (keys come out in sorted order — see the note on iteration order below):
host = example.com
port = 8080
timeout = 30
The pattern is always the same: hash keys gives you the keys, foreach walks them, hash get (or $config[$key] subscript syntax) reads each value.
$#hashname gives you the count of keys, just like arrays:
echo "$#config entries in config" # 3 entries in config
Or hash size config, which also sets $result.
A common job: read a KEY=VALUE config file into a hash for the rest of the script to consult by name. Here's a small loader:
proc load_config(path)
declare -A loaded
foreach line (`type $path`)
# Skip blank lines
if ("$line" == "") then
continue
endif
# Skip comments (lines starting with #) via grep
echo "$line" | grep -qE "^#"
if ($? == 0) then
continue
endif
# Split on first '='
set key = $(echo $line | cut -d'=' -f1)
set value = $(echo $line | cut -d'=' -f2)
hash set loaded $key $value
end
endproc
load_config app.conf
echo "Host: $loaded[host]"
echo "Port: $loaded[port]"
echo "Timeout: $loaded[timeout]"
With an app.conf like:
# Application configuration
host=example.com
port=8080
timeout=30
The procedure reads it, skipping comments, splitting each line on =, and populating a hash you can then consult by key. That's a real, useful pattern that turns up in nearly every nontrivial script.
TIP
Hashes are the right tool when your input has named fields you want to look up. Arrays are the right tool when your input is positional — the third item is meaningful as "the third item." Most config files want hashes; most processing pipelines want arrays.
TRY IT
Build an app.conf (a few lines of key=value plus some # comments) and run the load_config procedure above. Vary the keys, add comments, see what gets parsed and what gets skipped.
Let's pull everything together. Imagine you have a file inventory.txt with one item per line, format name,quantity,price:
widget,42,1.50
gadget,17,3.99
gizmo,8,12.00
sprocket,103,0.75
flange,29,4.25
We want a script that reads it, computes some summary statistics, and groups items by price tier.
# inventory.cshw — summarize inventory.txt
declare -a names
declare -a quantities
declare -a prices
# --- Load data into parallel arrays ---
foreach line (`type inventory.txt`)
set name = $(echo $line | cut -d',' -f1)
set qty = $(echo $line | cut -d',' -f2)
set price = $(echo $line | cut -d',' -f3)
array push names $name
array push quantities $qty
array push prices $price
end
# --- Compute totals ---
@ total_units = 0
@ total_value = 0 # in cents to avoid floats
foreach q ($quantities)
@ total_units = $total_units + $q
end
loop $#names as i
# convert dollars to cents by removing the dot and treating as integer
set p_cents = $(echo $prices[$i] | tr -d ".")
@ total_value = $total_value + $p_cents * $quantities[$i]
endloop
# --- Group items by price tier ---
declare -A by_tier
hash set by_tier cheap ""
hash set by_tier medium ""
hash set by_tier expensive ""
loop $#names as i
set p = $prices[$i]
set tier = "cheap"
if ($p > 2) then
set tier = "medium"
endif
if ($p > 10) then
set tier = "expensive"
endif
set current = $(hash get by_tier $tier)
hash set by_tier $tier "$current $names[$i]"
endloop
# --- Report ---
echo "=== Inventory Summary ==="
echo "Items: $#names"
echo "Total units: $total_units"
echo "Total value (cents): $total_value"
echo ""
echo "By price tier:"
foreach tier (`hash keys by_tier`)
echo " $tier: $(hash get by_tier $tier)"
end
Output on the sample data:
=== Inventory Summary ===
Items: 5
Total units: 199
Total value (cents): 39572
By price tier:
cheap: widget sprocket
medium: gadget flange
expensive: gizmo
That's a real, useful little tool, built entirely from the array and hash primitives plus the control flow from Chapter 9. The script touches every pattern in this chapter:
loop $#arr as i for indexed iterationforeach key (hash keys H) for hash walkingTECHNICAL STUFF
The "value in cents" trick — multiplying by 100 implicitly by removing the decimal point — sidesteps cshw's integer-only @ arithmetic. For real money calculations you'd want a proper fixed-point or decimal library; for a script that's just summarizing inventory, treating cents as integers is fine and accurate.
cshw's collections are deliberately simple. Some operations from other languages aren't built in:
pop, shift, or splice on arrays. The array command supports set / get / push / size / list — that's it. Shrinking an array or removing a specific element isn't a primitive operation. The workaround is to build a new array containing the elements you want to keep (the filter pattern from earlier in this chapter).hash delete. Once a key is set, the only way to "remove" it is to set its value to an empty string or some sentinel, and then check for that in your code. A true delete would be a useful future addition.hash set cell "row3_col5" "X". For genuinely tree-shaped data, you've outgrown shell collections and a real programming language is the right tool.hash keys and hash list walk the hash alphabetically by key. That's deterministic — same keys come out the same way every time — but if you specifically need insertion order, keep a parallel array of keys and iterate over that instead.These constraints are why shell scripting eventually hits a ceiling — and why cshw provides the genai command (Chapter 17) for when your data manipulation outgrows the shell's primitives. For the kinds of tasks shells are good at — config files, log processing, batch jobs, simple aggregations — what's there is plenty.
REMEMBER
When you start fighting the array/hash command surface, ask whether you're solving the right problem at the shell level. The shell is great at orchestration, pipelines, and small data wrangling. If you find yourself building elaborate data structures, that's usually the signal to either offload to a small Python/awk script (which cshw can invoke cleanly) or use genai to handle the heavy lifting.
Part III is done. You've moved through:
Linear scripts → branching → modular → data-aware. That's the full progression of shell scripting as it's practiced. Every script you've written so far has been small because we've been teaching one thing at a time. Now the pieces compose into real, complete tools.
Next up is Chapter 12 — arbitrary-precision math with bc and dc — and then Part IV, where cshw gets interesting. The features in those chapters are why cshw is more than a Unix shell ported to Windows — they're things that don't exist (or are awkward to use) anywhere else.
bg/fg/jobs/kill, controlling running processescorunproc / cowait / coresultfetch, ftpfetch, the low-level socket command, tcpserver and tcpclientgenai command, provider registration, asking, analyzing, code generationPart III gave you everything you need to write practical, useful scripts. Part IV gives you everything you need to be impressed by what your shell can do.
Bring the .cshrc. Things are about to get interesting.